简体   繁体   中英

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

I have two arrays and each one contain 14 items and a main for loop (I want i in this loop to do some behaviors).

I want to assign pass variable along with iterating i in the for loop with items of values array.

Here is what I mean:

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
}

If I understood correctly you want to check whether your indexs array contains index i of for variable. If so, try to use includes function:

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];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM