假设我有一个由对象组成的数组:
var points = [
{ id: 1, a: 0, b: 3 },
{ id: 2, a: 4, b: -1 },
{ id: 3, a: -1, b: 5 },
{ id: 4, a: 41, b: 2 },
{ id: 5, a: 69, b: 3 },
]
我想迭代每个项目并添加 a
+ b
以获取新项目 d
。然后我想在数组中的每个对象中添加 d 以获得新值。当我尝试下面的操作时,它只是添加 5 个额外的对象,而不是将新元素(键=值,例如:d:3)附加到每个单独的对象。我在这里做错了什么?
points.forEach((item) => {
var d = Math.abs(item.x) + Math.abs(item.y);
console.log(d);
points.item.push('d: ' + d);
});
最佳答案
尝试以下
var points = [{ id: 1, a: 0, b: 3 },{ id: 2, a: 4, b: -1 },{ id: 3, a: -1, b: 5 },{ id: 4, a: 41, b: 2 },{ id: 5, a: 69, b: 3 }];
points.forEach(o => o.d = Math.abs(o.a) + Math.abs(o.b));
console.log(points);
关于javascript - 向数组中的对象添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868481/