English 中文(简体)
比较Actionscript 3中的parseInt和NaN
原标题:Comparing parseInt to NaN in Actionscript 3

AS3文档指出,如果向parseInt传递一个不是数字的字符串,它将返回NaN。但是,当我尝试与NaN进行比较时,编译器会给我以下错误:

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

这句话实际上是对的。与NaN进行比较将始终返回false。如何与NaN进行比较,以检测解析的内容是否为NaN?

if( parseInt("test") == NaN )
{
   // do something (never gets here)
}
最佳回答

isNaN()函数进行比较。

问题回答

使用isNaN()全局函数

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

每个人都是正确的,请使用isNaN()函数:

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

我从来都不喜欢这种方法。我更喜欢检测阳性。

然而,有趣的是,如果一个数字是NaN,那么它将不等于本身:

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

因此,测试数字是否等于它本身应该会给你带来积极的结果:

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

在阅读代码时,您的意图不是很清楚,所以如果您使用它,请务必对其进行注释。

或者您可以添加一个顶级函数:

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

还有一个关于优化螺母的注释。内联版本是最快的。

仅供参考:http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/package.html#parseInt()





相关问题
Attaching a property to an event in Flex/AS3

I have a parameter that needs to be passed along with an event. After unsuccessful attempts to place it on the type by extending the class, I ve been advised in another SO question to write a custom ...

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

What s a good way of deserializing data into mock objects?

I m writing a mock backend service for my flex application. Because I will likely need to add/edit/modify the mock data over time, I d prefer not to generate the data in code like this: var mockData =...

AS3 try/catch out of memory

I m loading a few huge images on my flex/as3 app, but I can t manage to catch the error when the flash player runs out of memory. Here is the what I was thinking might work (I use ???? because i dont ...

热门标签