我有一个类似的数组
a=[1,2,3,,4,5];
所以现在我想找到缺失值索引,即 3
,使用 indexOf
。
最佳答案
检查值是否为undefined
,如下代码:
for ( var i = 0; i < a.length; i++ ) {
if ( typeof a[i] === "undefined" ) {
// do stuff here or break the loop
}
}
更新 您也可以这样做:
Array.prototype.indexOfUndefined = function() {
for ( var i = 0; i < this.length; i++ ) {
if ( typeof this[i] === "undefined" ) {
return i;
}
}
}
您需要返回i
,因为i
是当前索引,它将搜索第一个undefined
值。
关于javascript - 如何找到数组中缺失值的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30574147/