[1, 2, 3].indexOf(3) => 2
[1, 2, NaN].indexOf(NaN) => -1
[1, NaN, 3].indexOf(NaN) => -1
您可以使用Array.prototype.findIndex方法找出数组中NaN的索引
let index = [1,3,4,'hello',NaN,3].findIndex(Number.isNaN)
console.log(index)
您可以使用Array.prototype.includes检查阵列中是否存在NaN。它不会给你索引!!它将返回一个布尔值。如果存在NaN,则返回true,否则返回false
let isNaNPresent = [1,2,NaN,'ball'].includes(NaN)
console.log(isNaNPresent)
不要使用Array.prototype.indexOf
你不能在数组中使用Array.Prototype.indexOf to找到NaN的索引。因为indexOf在内部使用strict-equality-operator而NaN === NaN
评估为false
.So indexOf将无法在数组中检测到NaN
[1,NaN,2].indexOf(NaN) // -1
使用Number.isNaN
而不是isNaN
:
在这里,我选择Number.isNaN over isNaN。因为isNaN
将string literal
视为NaN
。另一方面,Number.isNaN
仅将NaN
文字视为NaN
isNaN('hello world') // true
Number.isNaN('hello world') // false
或者,编写自己的逻辑:
您可以编写自己的逻辑来查找NaN。正如您已经知道的那样,NaN是javascript中唯一的值not equal to itself
。这就是我建议不要使用Array.prototype.indexOf
的原因。
NaN === NaN // false
我们可以用这个想法来编写我们自己的isNaN函数。
[1,2,'str',NaN,5].findIndex(e=>e!=e) // 3
NaN被定义为不等于任何东西(甚至不是自己)。见这里:http://www.w3schools.com/jsref/jsref_isNaN.asp
您必须查看每个项目以返回NaN值的索引数组 -
function findNaNs(arr){
return arr.map(function(itm, i){
if(isNaN(itm)) return i;
return false;
}).filter(function(itm){
return itm;
});
}
findNaNs([1,NaN,3,4,'cat'/ 3])
//或找到第一个 -
function firstNaN(arr){
var i= 0, L= arr.length;
while(i<L){
if(isNaN(arr[i])) return i;
++i;
}
return -1;
}