如何检查数组中是否存在NaN关键字?

时间:2016-09-09 10:11:30

标签: javascript nan

我有以下数组

var arr = [7, 1, "abc", undefined, NaN];

但是如何检查arr中的值是否为NaN?

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || arr[i] === NaN) {
        // do something
    }

  }

任何想法?我尝试了isNaN(arr[i])功能,但它也无效。

5 个答案:

答案 0 :(得分:4)

对我而言,这是有效的吗?

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || Number.isNaN(arr[i]) ) {
        console.log("NaN");
    }

  }

答案 1 :(得分:3)

您可以检查类型(typeof NaN === 'number')和isNaN的{​​{1}}值。

NaN

check if the value is unequal to itself

var arr = [7, 1, "abc", undefined, NaN], i;
for (i = 0; i < arr.length; i++){
    if (typeof arr[i] === 'number' && isNaN(arr[i])) {
        console.log('Element ' + i + ' is NaN');
    }
}

答案 2 :(得分:1)

首先将值转换为String。然后查看value == 'NaN'

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || (arr[i] != undefined && typeof(arr[i]) == "number" && arr[i].toString() === 'NaN')) {
        // do something
    }

  }

答案 3 :(得分:1)

在ECMAScript 6中,您可以使用Number.isNaN函数:

var arr = [7, 1, "abc", undefined, NaN];

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || Number.isNaN(arr[i])) {
        console.log("NaN found at place " + i);
    }

  }

如果您需要在ECMAScript 5中工作,那么isNaN函数的问题在于它正在检查该值是否能够被强制转换为数字。相反,你可以使用NaN值的奇数属性 - 它不等于它自己:

var arr = [7, 1, "abc", undefined, NaN];

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || arr[i] != arr[i]) {
        console.log("NaN found at place " + i);
    }

  }

答案 4 :(得分:1)

isNan适合我:

for (i=0; i < arr.length; i++){
    // check if array value is false or NaN
    if (isNaN(arr[i])) {
        console.log("Not a number at index " + i + ": "+arr[i]);
    }
}

打印(在node.js中):

Not a number at index 2: abc
Not a number at index 3: undefined
Not a number at index 4: NaN