![](/img/trans.png)
[英]array.push(object) not pushed at the end of the loop in javascript
[英]Array.push() in a nested for loop causing last value of parent loop to be pushed
我有一个对象,它有两个带有数组值的键:
{
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] };
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; modifiedCommands.push(newCommand); } } console.log(modifiedCommands); }; const object = { list: ["a", "b", "c"], commands: [{ type: "LOAD_URL", url: "https://example.com" }] }; addListValueToCommands(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
你的问题在这里:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.