你如何在JavaScript中测试NaN? [英] How do you test for NaN in JavaScript?
问题描述
我有一个变量x,我想测试x是否设置为NaN。我该怎么做?
I have a variable x and I want to test if x is set to NaN. How do I do that?
我的第一直觉可能就是测试它,就像这样:
My first instinct is probably to, you know, test it, like this:
if (x === NaN) { ...
<傻兔子,不,那太容易了。 NaN在SQL中就像NULL,它不等于任何东西,甚至本身。
Silly rabbit, no, that would be far too easy. NaN is like NULL in SQL, it is not equal to anything, even itself.
但是看,有一个名为的函数isNaN()
- 也许会这样做!
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([])
正确返回false,但是 isNaN([。])
返回true。你不想知道我是如何了解这个漏洞的。
For example, isNaN([""])
properly returns false, but isNaN(["."])
returns true. You don't want do know how I learned about this flaw.
我该怎么做?
事实证明,我的问题与这个重复一个,但选择的答案是错误的。 正确答案的赞成数量为20%。
Turns out, my question is a duplicate of this one, but the selected answer is wrong. The right answer has 20% as many upvotes.
推荐答案
如果你仔细阅读,这个问题就有答案了。这就是我发现它的方式:我正在输入问题并且... bingo。
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.
你还记得当我写 NaN
在SQL中就像NULL,它不等于任何东西,甚至本身?据我所知, NaN
是Javascript中唯一具有此属性的值。因此你可以写:
You remember when I wrote "NaN
is like NULL in SQL, it is not equal to anything, even itself"? So far as I know, NaN
is the only value in Javascript with this property. Therefore you can write:
var reallyIsNaN = function(x) {
return x !== x;
};
这篇关于你如何在JavaScript中测试NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!