[英]Javascript Iterate elements of a first array at the position of another second array
hello i have the following code你好我有以下代码
let names = ["josh","tony","daniel"];
let arrayplaces = ["30", "60", "90"];
names.forEach((elem, indexed) => {
const num2 = arrayplaces[indexed];
console.log('The user ' + elem + ' iterated in place ' + num2);
});
What I'm looking for is to iterate through all the elements of the first array into the first element of the second array, ending with the first one and continuing until it goes through the entire second array.我正在寻找的是遍历第一个数组的所有元素到第二个数组的第一个元素,以第一个元素结束并继续直到它遍历整个第二个数组。
Example of the expected output:
The user josh iterated in place 30
The user tony iterated in place 30
The user daniel iterated in place 30
The user josh iterated in place 60
The user tony iterated in place 60
The user daniel iterated in place 60
The user josh iterated in place 90
The user tony iterated in place 90
The user daniel iterated in place 90
Does anyone know how I can do this?有谁知道我该怎么做?
You can do this by nesting loop both the array.您可以通过在两个数组中嵌套循环来做到这一点。
let names = ["josh","tony","daniel"]; let arrayplaces = ["30", "60", "90"]; arrayplaces.forEach((element)=>{ names.forEach((elem) => { console.log('The user ' + elem + ' iterated in place ' + element); }); console.log(''); });
You need to loop over both arrays.您需要遍历两个数组。
for (let place of arrayplaces) {
for (let name of names) {
console.log(`The user ${name} iterated in place ${place}`)
}
console.log('\n')
}
You just should eterate every value of arrayplaces
with every name.您只应该使用每个名称来arrayplaces
的每个值。 You should use 2 cycles to do that.您应该使用 2 个周期来执行此操作。
const names = ['josh', 'tony', 'daniel']; const arrayplaces = ['30', '60', '90']; names.forEach((elem, indexed) => { names.forEach((elem2) => { const num2 = arrayplaces[indexed]; console.log(`The user ${elem2} iterated in place ${num2}`); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.