簡體   English   中英

在迭代過程中將數組與var比較(續)

[英]Comparing array to var during iteration(cont.)

所以這是我的問題。可能會很累,但是,僅當數組中未出現數字時,我才想反++。

這意味着在4次迭代中,counter應該僅在迭代1,3,4時才++

var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
    array.push(i);
    number = temp[i];
}
document.write(counter);

但是我在這里畫一個空白...幫助嗎?

(不,這不是功課)

不幸的是,JS沒有“ in_array”,但是很簡單:
@MikeSamuel指出您可以使用indexOf(感謝Mike)。 話雖這么說:

var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
    array.push(i);
    number = temp[i];
    if (temp.indexOf(i)==-1) // much simpler, assuming you're checking if i is in temp.
      counter++; // increase counter if it is not.
}
document.write(counter);

我不確定您想在哪里使用邏輯,因此您必須弄清楚這一點或更具體。 只知道您需要遍歷要檢查的數組,並檢查“ needle”是否在“ haystack”數組中。

EDIT相反,只是添加了bool來檢查是否存在。

if (array.indexOf(number) < 0)
    counter++;

暫無
暫無

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

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