forEach在javascript中同时遍历两个数组 [英] forEach loop through two arrays at the same time in javascript
本文介绍了forEach在javascript中同时遍历两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想建立一个for
循环,该循环同时遍历两个变量. n
是一个数组,j
从0到16.
I want to build a for
loop that iterates through two variables at the same time. n
is an array and j
goes from 0 to 16.
var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
m.forEach(k => {
n.forEach(i => {
console.log(i, k)
});
};
最终结果应输出:
1,0
2,1
3,2
5,3
(...)
不幸的是,由于某些原因,该循环没有执行此操作,因为它会重复每个数字17次.
Unfortunately this loop doesn't do that for some reason as it repeats every number 17 times.
我在这里想念什么?
推荐答案
使用第二个参数forEach
代替,它将是您要遍历的当前索引:
Use the second parameter forEach
accepts instead, which will be the current index you're iterating over:
n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
n.forEach((element, index) => {
console.log(element, index);
});
如果您有两个单独的数组开头,则在每次迭代中,访问另一个数组的[index]
属性:
If you have two separate arrays to begin with, in each iteration, access the [index]
property of the other array:
var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];
var m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
n.forEach((num1, index) => {
const num2 = m[index];
console.log(num1, num2);
});
这篇关于forEach在javascript中同时遍历两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文