在JavaScript中如何检查一个数字是否为NaN?

544

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

parseFloat('geoff') == NaN;

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

6
如果您的实际目标是检查数字, 这篇文章值得一读:https://dev59.com/3nVD5IYBdhLWcg3wU56H - Paul
3
http://designpepper.com/blog/drips/the-problem-with-testing-for-nan-in-javascript.html - Foreever
1
@Gothdo:好的,但是我确实问过如何检查一个数字是否为NaN,而不是任何值。 - Paul D. Waite
3
@PaulD.Waite 是的,但很多人在谷歌搜索"如何在JavaScript中检查变量是否为NaN"时会来到这里。 - Michał Perłakowski
在ES6(又名ECMAScript 2015)中,使用Number.isNaN,查看此答案MDN - undefined
显示剩余4条评论
33个回答

2
我把这个答案写在了StackOverflow上,另一个人检查了NaN == null,但是后来它被标记为重复问题,所以我不想浪费我的工作。
请看Mozilla Developer Network上关于NaN的内容。

简短回答

当你想确保你的值是一个适当的数字时,请使用 distance || 0,或者使用 isNaN() 进行检查。

详细回答

NaN(非数字)是 JavaScript 中一个奇怪的全局对象,在某些数学运算失败时经常返回。

您想要检查 NaN == null,结果为 false。但是即使是 NaN == NaN 的结果也是 false

检查变量是否为 NaN 的一个简单方法是使用全局函数 isNaN()

另一个方法是使用 x !== x,只有当 x 是 NaN 时才为 true。(感谢 @raphael-schweikert 提醒)

但为什么简短回答有效呢?

让我们找出原因。

当您调用 NaN == false 时,结果为 false,与 NaN == true 相同。

在 JavaScript 的规范中,有一个包含始终为 false 值的记录,其中包括:

  • NaN - 非数字(Not-a-Number)
  • "" - 空字符串
  • false - 布尔值假
  • null - 空对象
  • undefined - 未定义的变量
  • 0 - 数值0,包括+0和-0

1
“只有通过全局函数 isNaN() 才能简单地判断变量是否为 NaN” 这是不正确的;还有另一种简单的方法: var xIsNaN = x !== x; 只有当 x 是 NaN 时才返回 true。 - Raphael Schweikert

2
根据IEEE 754标准,所有涉及NaN的关系都会被判定为false,除了!=。因此,例如,如果A或B或两者都是NaN,则(A>=B)=false且(A<=B)=false。

2

发现了另一种方法,只是为了好玩。

function IsActuallyNaN(obj) {
  return [obj].includes(NaN);  
}

0
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);

这不是很优雅,但在尝试了isNAN()之后,我找到了另一种解决方案。在这个例子中,我也允许使用'.',因为我正在掩盖浮点数。你也可以反过来,确保不使用任何数字。

("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)

这是一个单个字符的评估,但您也可以循环遍历字符串以检查任何数字。


0

检查的确切方法是:

//takes care of boolen, undefined and empty

isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'

0
我创建了一个小函数,它非常好用。 与检查NaN相比,这种方法更直观,你可以检查数字。我相信我不是第一个这样做的人,但我想分享一下。
function isNum(val){
    var absVal = Math.abs(val);
    var retval = false;
    if((absVal-absVal) == 0){
        retval = true
    }

    return retval;
}

0
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

0
发现这个很有用
    // 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;

0

尝试在条件中同时使用两个

if(isNaN(parseFloat('geoff'))  && typeof(parseFloat('geoff')) === "number");
//true

0

marksyzm的答案很好,但对于Infinity并不返回false,因为从技术上讲Infinity不是一个数字。

我想出了一个isNumber函数来检查它是否是一个数字。

function isNumber(i) {
    return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}

console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));

更新: 我注意到这段代码对于某些参数会失败,所以我进行了改进。

function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
 } else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
 } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
 } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
 } else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
 } else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
 } else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
 }
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));


你的前提“无穷大在技术上不是一个数字”在技术上是错误的:https://math.stackexchange.com/questions/36289/is-infinity-a-number。从答案中我所阅读到的是,无穷大是否是数字取决于上下文。 - Jon P
我将把这个移到另一个问题。 - adddff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接