【问题标题】:How can I use one forEach loop to iterate over two different arrays?如何使用一个 forEach 循环遍历两个不同的数组?
【发布时间】:2017-06-13 10:32:41
【问题描述】:

我希望能够通过一个 forEach 循环将这两个数组的值记录到控制台上。截至目前,我只迭代第一个,因为这就是我所知道的全部!这可能吗?

var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8];

array1.forEach(function(item){
    console.log(item)
});

【问题讨论】:

  • 您可以遍历索引而不是遍历项目本身,然后使用索引访问循环内的项目。

标签: javascript arrays function loops foreach


【解决方案1】:

如果两个数组的长度相同,那么您可以使用index 记录其他数组中的元素。

var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8];

array1.forEach(function(item, index){
  console.log(item, array2[index])
});

【讨论】:

    【解决方案2】:

    您可以使用concat 将它们连接在一起,所以:

    var array1 = [1, 2, 3, 4];
    var array2 = [5, 6, 7, 8];
    
    array1.concat(array2).forEach(function(item){
        console.log(item)
    });
    

    在不同的行上打印 1、2、3、4、5、6、7、8。

    【讨论】:

      【解决方案3】:
      var array1 = [1, 2, 3, 4];
      var array2 = [5, 6, 7, 8];
      
      array1.forEach(function(item, i){
        console.log(item, array1[i]) // logs first array
        console.log(item, array2[i])// logs second array
      });
      

      【讨论】:

        【解决方案4】:

        另一种解决方案是将数组合并为一个,就像这样,假设顺序对您很重要:

        const combined = array1.map((array1val, index) => [array1val, array2[index]])
        
        combined.forEach(vals => {
          vals.forEach(console.log)
        })
        

        【讨论】:

          【解决方案5】:

          我们也可以像这样使用'for'循环来迭代两个数组:

          for(i=0;i < array1.length || i < array2.length;i++){
              console.log(array1[i] + '----' + array2[i])
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-06-07
            • 2017-06-08
            • 2021-10-08
            • 2011-05-25
            • 2020-01-14
            • 2015-07-11
            相关资源
            最近更新 更多