我有以下代码:
if (array.indexOf("undefined")===-1){
do something...
}
我的初始数组是:
阵列= [,,,,,,];
随着程序的继续,它会被填充值但我希望函数在没有未定义的空格时停止。上面的语法虽然不正确。任何人都可以告诉我原因。
答案 0 :(得分:0)
for(var ind in array) {
if(array[ind] === undefined) {
doSomething();
}
}
答案 1 :(得分:0)
您的检查无效,因为您传递了字符串"undefined"
而不是值本身。此外,.indexOf()
旨在明确忽略数组中的漏洞。
使用迭代来检测数组中的漏洞似乎很浪费。相反,您可以通过使用计数器跟踪已填充的孔数,并在计数器与长度匹配时执行代码。
无论哪种方式,在特定索引处检测孔的正确方法是使用in
运算符。
这是一个基于类的重用解决方案:
class SpacesArray extends Array {
constructor(n, callback) {
super(n);
this.callback = callback;
this.counter = 0;
}
fillHole(n, val) {
if (!(n in this)) {
this.counter++;
console.log("filling hole", n);
}
this[n] = val;
if (this.counter === this.length) {
this.callback();
}
}
}
// Usage
var sa = new SpacesArray(10, function() {
console.log("DONE! " + this);
});
// Emulate delayed, random filling of each hole.
for (let i = 0; i < sa.length; i++) {
const ms = Math.floor(Math.random() * 5000);
setTimeout(() => sa.fillHole(i, i), ms);
}
&#13;