【问题标题】:nodejs/JS: Objects not being updated in array [duplicate]nodejs / JS:数组中未更新的对象[重复]
【发布时间】:2020-09-20 04:59:34
【问题描述】:

首先,我完全是 Javascript 和 Node.js 的菜鸟。

我尝试编写一个简单的程序来创建一个平面数组,这些平面数组除了索引之外都具有相同的值,它应该采用 for 循环中从 0 到 2 的每个索引的值。

这是我的代码

var plane = {
    index: -1,
    name: "A380",
    seats: {
        first: 40,
        buisness: 90,
        economy: 300
    },
    wheels: 8,
}

var planeArray = []

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(plane)
  }

  console.log(planeArray)

但是当我打印输出时,所有平面的索引都是 2。这是我的输出。

[
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

这是我的预期输出。

[
  {
    index: 0,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 1,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

我不明白为什么。 有人可以帮帮我。此外,任何有助于学习 node.js 的其他解释/资源将不胜感激

【问题讨论】:

  • 您将同一个对象多次推送到数组中。不是多个不同的对象。
  • 这在 JS 中称为对象变异。最好在继续之前阅读此内容。 zeptobook.com/object-mutation-in-javascript
  • 或者,改为const plane = (index) =&gt; ({ index, name: "A380", …等… });,在你的for循环中只使用planeArray.push(plane(i));。更好的是 const planeArray = Array.from({ length: 3 }, (_, index) =&gt; plane(index)); 而不是整个 for 循环。

标签: javascript arrays node.js json for-loop


【解决方案1】:

这里的问题是被添加到数组中的对象是作为引用而不是作为对象的值 您可以尝试以下两种解决方案中的任何一种。 这样你传递对象值而不是它的引用。

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push({...plane})
  }
for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(JSON.parse(JSON.stringify(plane)))
  }

【讨论】:

  • JSON.stringify |&gt; JSON.parse 并不优雅,不适用于所有类型的对象和数据类型; { ...plane } 仅复制顶层属性 — 嵌套的 seats 对象仍将具有相同的引用。
【解决方案2】:

您总是用plane.index = i 更改同一个对象。如果您想在数组中包含三个不同的条目,则需要三个不同的对象。

【讨论】:

  • 您最好提供一个示例解决方案的详细说明。
  • 感谢您的反馈。以后会做的。
猜你喜欢
  • 2021-10-20
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 2021-11-11
  • 2018-08-23
  • 2017-09-02
  • 2018-06-26
相关资源
最近更新 更多