繁体   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