我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:

parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;

当前回答

我在StackOverflow上写了另一个问题的答案,当NaN == null时,另一个检查,但它被标记为重复,所以我不想浪费我的工作。

看看关于NaN的Mozilla开发者网络。


简短的回答

只要使用距离|| 0当你想确保你的值是一个正确的数字或isNaN()检查它。

长回答

NaN (Not-a-Number)是javascript中一个奇怪的全局对象,当某些数学操作失败时,经常返回。

你想检查NaN == null,结果是false。然而,即使NaN == NaN结果为假。

判断变量NaN是否为全局函数的一个简单方法是NaN()。

另一个是x !== x,仅当x为NaN时才成立。(感谢提醒@raphael-schweikert)

但为什么这个简短的答案管用呢?

让我们一探究竟。

当你调用NaN == false时,结果是假的,NaN == true也是一样。

在规范中,JavaScript有一个总是false值的记录,包括:

NaN -不是一个数字 "" -空字符串 False -布尔值为False Null - Null对象 Undefined -未定义的变量 0 -数字0,包括+0和-0

其他回答

使用以下代码:

isNaN('geoff');

参见MDN上的isNaN()文档。

alert ( isNaN('abcd'));  // alerts true
alert ( isNaN('2.0'));  // alerts false
alert ( isNaN(2.0));  // alerts false

我只想分享另一种选择,它不一定比这里的其他选择更好,但我认为它值得一看:

function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }

这背后的逻辑是,除了0和NaN之外的所有数字都被转换为true。

我做了一个快速测试,它的性能和Number一样好。isNaN和as检查自身是否为false。这三个都比isNan表现得好

结果

customIsNaN(NaN);            // true
customIsNaN(0/0);            // true
customIsNaN(+new Date('?')); // true

customIsNaN(0);          // false
customIsNaN(false);      // false
customIsNaN(null);       // false
customIsNaN(undefined);  // false
customIsNaN({});         // false
customIsNaN('');         // false

如果您想避免损坏的isNaN函数,可能会很有用。

发现这很有用

    // Long-hand const isFalsey = (value) => {   if (
        value === null ||
        value === undefined ||
        value === 0 ||
        value === false ||
        value === NaN ||
        value === ""   ) {
        return true;   }   return false; };
 // Short-hand const 
      isFalsey = (value) => !value;
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
    
Number('12345').toString() === 'NaN' // false  

// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0

// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1

对此我看到了一些回应,

但我只用:

function isNaN(x){
     return x == x && typeof x == 'number';
}