首页 > 解决方案 > 嵌套 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' }
]

我以前从未遇到过这样的事情。我试过弄乱不同的变量范围,克隆数组和命令对象,但我似乎无法得到任何工作。

标签: javascriptnode.jsarraysjavascript-objects

解决方案


你的问题在这里:

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))


推荐阅读