简体   繁体   English

你如何在 JavaScript 中测试 NaN?

[英]How do you test for NaN in JavaScript?

I have a variable x and I want to test if x is set to NaN.我有一个变量 x,我想测试 x 是否设置为 NaN。 How do I do that?我怎么做?

My first instinct is probably to, you know, test it, like this:我的第一直觉可能是,你知道,测试它,像这样:

if (x === NaN) {  ...

Silly rabbit, no, that would be far too easy.傻兔子,不,那太容易了。 NaN is like NULL in SQL, it is not equal to anything, even itself. NaN 就像 SQL 中的 NULL,它不等于任何东西,甚至它本身。

But look, there is a function called isNaN() -- maybe that will do it!但是看,有一个名为isNaN()的函数——也许可以做到!

No, so far as I can tell, isNaN() is utterly worthless.不,据我所知, isNaN()完全没有价值。

For example, isNaN([""]) properly returns false, but isNaN(["."]) returns true.例如, isNaN([""])正确返回 false,但isNaN(["."])返回 true。 You don't want do know how I learned about this flaw.你不想知道我是怎么知道这个缺陷的。

How do I do this?我该怎么做呢?

Turns out, my question is a duplicate of this one , but the selected answer is wrong.原来,我的问题与这个问题重复,但选择的答案是错误的。 The right answer has 20% as many upvotes.正确答案有 20% 的赞成票。

Short Answer简答

For ECMAScript-5 Users:对于 ECMAScript-5 用户:

#1
if(x !== x) {
    console.info('x is NaN.');
}
else {
    console.info('x is NOT a NaN.');
}

For people using ECMAScript-6:对于使用 ECMAScript-6 的人:

#2
Number.isNaN(x);

And For consistency purpose across ECMAScript 5 & 6 both, you can also use this polyfill for Number.isNan并且为了在 ECMAScript 5 和 6 中保持一致性,您还可以将这个polyfill 用于 Number.isNan

#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
    return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

Note: I prefer to test using #1 which works same all places and does not have dependency on latest JS also.注意:我更喜欢使用 #1 进行测试,它在所有地方都适用,并且也不依赖于最新的 JS。 (It always gives me correct result. No surprises!) (它总是给我正确的结果。没有惊喜!)


Detailed Explanation:详细说明:

Here is our awesome NaN这是我们很棒的 NaN

NaN == NaN; // false
NaN === NaN; // false

Please don't blame JavaScript for this, it is NaN which is supposed to behave this way in other languages also Which is fine as per rationale for all comparisons returning false NaN values请不要为此责怪JavaScript ,NaN 在其他语言中也应该以这种方式表现根据所有返回错误 NaN 值的比较的基本原理,这很好

So comes isNaN as our savior, but wait it acts little differently in some scenarios like所以isNaN作为我们的救星来了,但是在某些情况下,它的行为有点不同,比如

isNaN(undefined); // true
isNaN({});        // true
isNaN("lorem ipsum"); // true

I had some strange faces by seeing the results above.看到上面的结果,我有一些奇怪的面孔。 And here comes reason from MDN这就是来自 MDN 的原因

When the argument to the isNaN function is not of type Number, the value is first coerced to a Number.当 isNaN 函数的参数不是 Number 类型时,该值首先被强制转换为 Number。 The resulting value is then tested to determine whether it is NaN.然后测试结果值以确定它是否为 NaN。

So how should we test NaN for the non-numbers variables at all?那么我们应该如何测试非数字变量的 NaN 呢? I always go by the following我总是遵循以下

if(x !== x) {
    console.info('Is a NaN');
}
else {
    console.info('Not a NaN');
}

ECMAScript-6/JavaScript-2015 Updates ECMAScript-6/JavaScript-2015 更新

Do we have anything in ECMAScript-6 for the same.我们在 ECMAScript-6 中有什么相同的吗? Yup we do...是的,我们确实...

Number.isNaN(x); // true

The ES6 implementation will also be helpful for the above cases like ES6 实现也将有助于上述情况,例如

Number.isNaN(undefined); // false
Number.isNaN({}); // false    
Number.isNaN("lorem ipsum"); // false

whereas ECMAScript-5 global function isNaN outputs in true for the above cases, which sometimes may not align with our expectation.而 ECMAScript-5 全局函数isNaN在上述情况下输出为true ,这有时可能与我们的预期不一致。

The question has the answer if you read closely enough.如果你仔细阅读,这个问题就有答案。 That is the way I found it: I was typing out the question and... bingo.这就是我找到它的方式:我正在输入问题并且......宾果游戏。

You remember when I wrote " NaN is like NULL in SQL, it is not equal to anything, even itself"?你还记得我写过“ NaN就像 SQL 中的 NULL,它不等于任何东西,甚至它本身”吗? So far as I know, NaN is the only value in Javascript with this property.据我所知, NaN是 Javascript 中唯一具有此属性的值。 Therefore you can write:因此你可以写:

var reallyIsNaN = function(x) {
   return x !== x;
};

It looks like an overkill but how about trying this?:这看起来有点矫枉过正,但试试这个怎么样?:

if (Number(dataInput) !== Number(dataInput))
{
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM