簡體   English   中英

分配一個變量並使用另一個數組的項目迭代 for 循環

[英]assign a variable along with iterating for loop with items of another array

我有兩個數組,每個數組包含 14 個項目和一個主要的 for 循環(我希望i在這個循環中做一些行為)。

我想分配pass變量,並在for loop使用values數組的項目迭代i

這就是我的意思:

var values = [1, 3, 1, 1, 1, 1, 2, 1, 2, 1, 2, 2, 1, 3];
var indexs = [3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
var pass = 0;
for (var i = 0; i < 1000; i++) { 
    // when i is equel to each item in "indexs" array assign "pass" with "values" item
    // for example if i == 3  ===>  pass = values[0] or 1
    // if i == 5  ===>  pass = values[1] or 3
    // if i == 18  ===>  pass = values[14] or 3
}

如果我理解正確的話,你要檢查你是否indexs數組包含索引ifor變量。 如果是這樣,請嘗試使用includes功能:

const values = [1, 3, 1, 1, 1, 1, 2, 1, 2, 1, 2, 2, 1, 3];
const indexs = [3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
let pass = 0;
for (let i = 0; i < 14; i++) { 
    if (indexs.includes(i)) {
      let arrayIndex = indexs.indexOf(i);
      pass = indexs[arrayIndex];
    }
}

暫無
暫無

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

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