首页 > 解决方案 > 嵌套的 forEach 在 Javascript 中无法按预期工作

问题描述

我遇到了这个函数的问题,它的工作方式应该与 Lodash _.zip([arrays])相同

简而言之,zip(['a', 'b'], [1, 2], [true, false]);应返回[['a', 1, true], ['b', 2, false]]

我的功能:

function zip(...array) {
  const newArr = Array(array[0].length).fill([]);
  array.forEach((el, i) => {
    el.forEach((item, idx) => {
      //   newArr[idx][i] = item;
      newArr[idx].push(item);
    });
  });
  return newArr;
}

相反,它返回: [ [ 'a', 'b', 1, 2, true, false ], [ 'a', 'b', 1, 2, true, false ] ]

有什么可以写错的?

标签: javascriptarraysloopsforeach

解决方案


当您调用时,fill您正在使用相同的数组填充数组,因此当您推送到索引 0 处的数组时,您也会推送到索引 1 处的数组。您可以通过首先填充数组然后调用map.

您还应该遍历新数组中的每个项目,然后遍历每个参数并在外部循环的索引处获取项目。

function zip(...array) {
  const newArr = Array(array[0].length).fill().map(u => ([]));
  newArr.forEach((item, i) => {
    array.forEach((a) => {
      item.push(a[i])
    })
  })
  return newArr;
}

console.log(JSON.stringify(zip(['a', 'b'], [1, 2], [true, false])))


推荐阅读