javascript - 嵌套的 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 ] ]
有什么可以写错的?
解决方案
当您调用时,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])))
推荐阅读
- javascript - 在不影响 PageSpeed 的情况下加载第三方 JS
- django - 从购物车中删除按钮在 django 中不起作用?
- ios - 返回屏幕后释放 UITableViewCell 的高亮状态
- azure - PowerBI MicrosoftAzureConsumptionInsights - 更改查询以获得超过 2 个月
- c++ - macOS Catalina 录屏权限
- java - JPA Postgres - 无法将动态 JSON 转换为 Java 类型
- matlab - 在 uitab 上创建具有多个轴的图。在 Matlab 中使用 addaxis
- java - Java 8:如何检查对象的所有字段是否为 NULL,除了一个
- user-interface - 我想从剪贴板复制、粘贴和剪切 CEdit 中的内容
- powershell-3.0 - 在 power-shell 工作流中使用 CSV 导入