【发布时间】: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) => ({ index, name: "A380",…等…});,在你的for循环中只使用planeArray.push(plane(i));。更好的是const planeArray = Array.from({ length: 3 }, (_, index) => plane(index));而不是整个for循环。
标签: javascript arrays node.js json for-loop