中同时循环遍历两个数组

中同时循环遍历两个数组

本文介绍了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 中同时循环遍历两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:43