javascript - 嵌套 for 循环中的 Array.push() 导致父循环的最后一个值被推送
问题描述
我有一个对象,它有两个带有数组值的键:
{
list: ["a", "b", "c"],
commands: [
{
type: "LOAD_URL",
url: "https://example.com",
},
],
}
我需要遍历 Object.list 数组,并将其值添加到每个 Object.commands 对象中。我编写了以下函数来实现这一点:
const addListValueToCommands = (valuesObj) => {
let modifiedCommands = [];
for (let a = 0; a < valuesObj.list.length; a++) {
let currentListValue = valuesObj.list[a];
for (let b = 0; b < valuesObj.commands.length; b++) {
let newCommand = valuesObj.commands[b];
newCommand.currentVal = currentListValue;
console.log(newCommand) // NOTE: logs correctly
modifiedCommands.push(newCommand); // NOTE: pushes incorrectly
}
}
console.log(modifiedCommands); // NOTE: logs wrong data
};
目标是让它返回:
[
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'a' },
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'b' },
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'c' }
]
但是它返回:
[
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'c' },
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'c' },
{ type: 'LOAD_URL', url: 'https://example.com', currentVal: 'c' }
]
我以前从未遇到过这样的事情。我试过弄乱不同的变量范围,克隆数组和命令对象,但我似乎无法得到任何工作。
解决方案
你的问题在这里:
let newCommand = valuesObj.commands[b]
所以newCommand
在你的命令数组中有一个条目的引用——当你的变量b
随着循环的运行而改变时,这个引用就会在你的脚下改变。
Array.map
您可以通过使用扩展运算符来复制命令来降低循环复杂性并修复错误:
const data = {
list: ["a", "b", "c"],
commands: [
{
type: "LOAD_URL",
url: "https://example.com",
},
],
}
const translateData = ({list,commands}) =>list.map(d=>({currentVal:d, ...commands[0]}))
console.log(translateData(data))
推荐阅读
- xamarin.uwp - 在 Xamarin ListView 中调用 ScrollTo 方法时 UWP UI 冻结
- angular - ngModel 没有更新 ionic 3 中的输入类型
- python - BeautifulSoup4 找不到正确的元素
- ios - Swift 4 SpriteKit 检测联系人
- database - 出现 SQL 错误:ORA-01847:运行我的语句时,月中的某天必须介于 1 和月的最后一天之间
- java - 我想在可编辑 JTable 的单元格中写入时更改字体大小
- angular - Angular 4:从服务返回承诺进入无限循环
- android - Android studio3.1:插件Android支持中的异常
- ios - npm install -g ios-deploy 没有工作,它显示错误
- python - Pandas:如何在一个日期范围内对列值求和