[英]Javascript Iterate elements of a first array at the position of another second array
你好我有以下代碼
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);
});
我正在尋找的是遍歷第一個數組的所有元素到第二個數組的第一個元素,以第一個元素結束並繼續直到它遍歷整個第二個數組。
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
有誰知道我該怎么做?
您可以通過在兩個數組中嵌套循環來做到這一點。
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(''); });
您需要遍歷兩個數組。
for (let place of arrayplaces) {
for (let name of names) {
console.log(`The user ${name} iterated in place ${place}`)
}
console.log('\n')
}
您只應該使用每個名稱來arrayplaces
的每個值。 您應該使用 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.