How can i simply check if a returned value of type int
or uint
is a number?
问题:
回答1:
Simple:
if(_myValue is Number)
{
fire();
}// end if
[UPDATE]
Keep in mind that if _myValue
is of type int
or uint
, then (_myValue is Number)
will also equate to true
. If you want to know if _myValue
is a number that isn't an integer(int) or unsigned integer (uint), in other words a float, then you can simply modify the conditional as follows:
(_myValue is Number && !(_myValue is int) && !(_myValue is uint))
Let's look at an example:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var number1:Object = 1; // int
var number2:Object = 1.1; // float
var number3:Object = 0x000000; // uint
trace(number1 is Number); // true
trace(number2 is Number); // true
trace(number3 is Number); // true
trace(number1 is Number && !(number1 is int) && !(number1 is uint)); // false
trace(number2 is Number && !(number2 is int) && !(number2 is uint)); // true
trace(number3 is Number && !(number3 is int) && !(number3 is uint)); // false
}
}
}
回答2:
If you only want to know if myValue is one of the numeric types (Number, int, uint), you can check if (_myValue is Number)
as Taurayi suggested.
If you also want to know if _myValue is a numeric string (like "6320" or "5.987"), use this:
if (!isNaN(Number(_myValue)))
{
fire();
}
It uses Number(_myValue)
to cast _myValue
to the Number
class. If Number
is unable to convert it into a useful number it will return NaN
, so we use !isNaN()
to make sure the returned value is not "not a number".
It will return true for any variable of type Number
(as long as its value isn't NaN
), int
, uint
, and strings that contain a valid representation of a number.
回答3:
These methods could be problematic if you wish to check the input of a text field, which is 'always' a string. If you have a string with "123" and check with "123" is Number, you will get a false. So Number("123") would give true, but then again so will Number("lalala") (event though the result is NaN which will tell you NaN is Number (true).
To work with string you could do:
var s:String = "1234";
String(Number(s)) == String(s);
--True
var s:String = "lalala";
String(Number(s)) == String(s);
--False
回答4:
There are
- isNaN (You will want to negate this)
- typeof (Not sure how strongly type Number works)
- and is (which was already mentioned, again I am not sure how strong, types hold)