开发者

Comparing parseInt to NaN in Actionscript 3

开发者 https://www.devze.com 2023-01-20 18:05 出处:网络
The AS3 documentation states that if you pass in a string to parseInt that is not a number it will return NaN. However, when I try to compare to NaN the compiler gives me the following error:

The AS3 documentation states that if you pass in a string to parseInt that is not a number it will return NaN. However, when I try to compare to NaN the compiler gives me the following error:

Warning: 1098: Illogical comparison with NaN. This statement always evaluates to false.

The statement is actually true. Comparing to NaN will always return false. How can I compare to NaN to detect if what was parsed was NaN?

if( parseInt("test") == NaN )
{
   //开发者_开发技巧 do something (never gets here)
}


Compare with isNaN() function.


Use isNaN() global function

if(isNaN(parseInt("test")))
{
   // do something 
}


Everyone is correct, use the isNaN() function:

http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/package.html#isNaN()

I've never really liked this method. I prefer to test for positives.

Interestingly though, if a Number is NaN then it will not equate to itself:

var parsed_int:Number = parseInt("test");
if(parsed_int != parsed_int)
  trace("NaN");

Therefor, testing if the Number equates to itself should give you the positive:

var parsed_int:Number = parseInt("123");
if(parsed_int == parsed_int)
  trace("Number");

It's not very clear what your intentions are when reading the code, so be sure to comment it if you use it.

Or you could add a top-level function:

function isNumber(num:Number):Boolean{
  return num == num;
}

And a note for the optimisation nuts out there. The inline version is fastest.

Just for reference: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/package.html#parseInt()

0

精彩评论

暂无评论...
验证码 换一张
取 消