【问题标题】:Nested forEach does not work as expected in Javascript [closed]嵌套的 forEach 在 Javascript 中无法按预期工作 [关闭]
【发布时间】:2021-12-04 12:36:49
【问题描述】:

这个函数有问题,应该和 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 ] ]

什么地方写错了?

【问题讨论】:

  • 在调试器中单步执行代码会显示什么?
  • 您正在对数组输入使用展开运算符。这会将数组的每个项目扩展为一个单独的参数。我认为这不是您想要的功能,因为您尝试使用与数组相同的输入。尝试删除扩展运算符

标签: javascript arrays loops foreach


【解决方案1】:

当您调用 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])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多