Javascript nodejs/JS:数组中未更新的对象
首先,我完全是Javascript和Node.js的新手。Javascript nodejs/JS:数组中未更新的对象,javascript,arrays,node.js,json,for-loop,Javascript,Arrays,Node.js,Json,For Loop,首先,我完全是Javascript和Node.js的新手。 [ { 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: 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
}
]
我试图编写一个简单的程序,创建一个平面数组,除了索引中的值外,所有平面都具有相同的值,索引中的值应该从0到2取for循环中每个索引的值
这是我的代码
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)
这是我的预期输出。
[
{
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的其他说明/资源,我们将不胜感激您总是使用
plane.index=i
更改同一对象。如果要在数组中有三个不同的条目,则需要三个不同的对象。这里的问题是,添加到数组中的对象作为引用,而不是对象的值
您可以尝试以下两种解决方案之一。
这样可以传递对象值而不是其引用
for (var i = 0; i < 3; i++) {
plane.index = i
planeArray.push({...plane})
}
for(变量i=0;i<3;i++){
平面指数=i
planeArray.push({…plane})
}
for(变量i=0;i<3;i++){
平面指数=i
planeArray.push(JSON.parse(JSON.stringify(plane)))
}
您多次将同一对象推入数组。不是多个不同的对象。这在JS中称为对象变异。你最好在继续之前读一下。或者,将其设置为const plane=(index)=>({index,name:“A380”,
…等…})相反,在for
循环中,只需使用planeArray.push(平面(i))代码>。更好的方法是constplanearray=Array
而不是整个for
循环。最好用示例解决方案提供详细解释。感谢反馈。将来就可以了。JSON.stringify |>JSON.parse
不是很优雅,也不适用于所有类型的对象和数据类型<代码>{…平面}
仅复制顶层属性 — 嵌套的seats
对象仍将具有相同的引用。