Thi*_*ker 7 javascript arrays jquery
我有一个类似的数组
a=[1,2,3,,4,5];
Run Code Online (Sandbox Code Playgroud)
所以现在我想找到缺失值索引,即3使用indexOf.
检查值是否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/
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 但这也是一个很好的解决方案。你应该尝试这个。