簡體   English   中英

尋找未定義值的正確方法是什么

[英]What is the proper way to look for undefined value

我有以下代碼:

if (array.indexOf("undefined")===-1){
    do something...
  }

我的初始數組是這樣的:

array = [,,,,,];

隨着程序的進行,它充滿了值,但是我希望函數在沒有未定義的空格時停止。 上面的語法雖然不正確。 任何人都可以告訴我原因。

您的代碼將查找字符串“ undefined”。 您要查找包含undefined值的第一個索引。 最好的方法是使用findIndex

if(array.findIndex(x=>x===undefined) !== -1) {
  //do something
}
for(var ind in array) {
 if(array[ind] === undefined) {
   doSomething();
 }
}

您的檢查不起作用,因為您傳遞了字符串"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); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM