« Wayback Machine | Main | VRML...not quite dead yet. »

Help, when is a number a Number?

So, I'm debugging some code...and trying something I haven't used before. I've used my_array instanceof Array, and it works just fine. But when I try to use num instanceof Number, not so good. Does anyone know why this code gives me a "false":

var n:Number = 3;


var isnum = n instanceof Number;
trace("n a number " + isnum);


Keep in mind that there are two different beasts at work here, when you are using instanceof it is comparing your value to the "Number" class which is an extension of the "object" primitive, not the "number" primitive. The same goes for "String" and "string"...

var n:Number = 3;
trace(n instanceof Number); // false
trace(typeof n); // number

var n:Number = new Number(3);
trace(n instanceof Number); // true
trace(typeof n); // object

var s:String = "String";
trace(s instanceof String); // false
trace(typeof s); // string

var s:String = new String("String");
trace(s instanceof String); // true
trace(typeof s); // object

Thanks Casey!

That clears up a lot!

You could also use 'isNaN' for numbers, which returns 'false' when the argument is not a number and true when it is.

var n:Number = 3;
trace(isNaN(n)); // false
var n1:Number = new Number(5);
trace(isNaN(n1)); // false
var str:String = "string";
trace(isNaN(str)); // true

Ofcourse I meant to say:
You could also use 'isNaN' for numbers, which returns 'false' when the argument is a number and true when it is not. :)