如何在数组中找到缺失值的索引?

Thi*_*ker 7 javascript arrays jquery

我有一个类似的数组

a=[1,2,3,,4,5];
Run Code Online (Sandbox Code Playgroud)

所以现在我想找到缺失值索引,即3使用indexOf.

Rad*_*ina 6

检查值是否undefined与以下代码类似:

for ( var i = 0; i < a.length; i++ ) {
    if ( typeof a[i] === "undefined" ) {
        // do stuff here or break the loop
    }
}
Run Code Online (Sandbox Code Playgroud)

更新 您也可以这样做:

Array.prototype.indexOfUndefined =  function() {
    for ( var i = 0; i < this.length; i++ ) {
        if ( typeof this[i] === "undefined" ) {
            return i;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要返回i因为i是当前索引,它将搜索第一个undefined值.

演示:http://jsfiddle.net/vdyypq6o/5/

  • @RadonirinaMaminiaina,所以,你的方法不仅找到_missed_值,还找到_undefined_值 (2认同)

dan*_*haj 0

a = [1,2,3,,4,5];
i = 0;
$.each(a , (function(){
  if(a[i]=="") {
    alert(i + ":: yes this is null index");
  }
  i++;
});
Run Code Online (Sandbox Code Playgroud)

您可以使用each 循环来达到此目的。市场上可能有更多用于此目的的解决方案 :P 但这也是一个很好的解决方案。你应该尝试这个。