如何在javascript中添加一个对象到数组

How to append an object to array in javascript?

本文关键字:一个对象 数组 添加 javascript      更新时间:2023-09-26

为什么数组只得到最后一个对象?

this.checkpoints = new Array();
this.checkpoint = new Object();
    this.checkpoint['lat'];
    this.checkpoint['lng'];
this.checkpoint['lat'] = 1;
this.checkpoint['lng'] = 1;
this.checkpoints.push(this.checkpoint);
this.checkpoint['lat'] = 2;
this.checkpoint['lng'] = 2;
this.checkpoints.push(this.checkpoint);
this.checkpoint['lat'] = 3;
this.checkpoint['lng'] = 3;
this.checkpoints.push(this.checkpoint);
console.log(this.checkpoints);

结果是错误的:

[Object { lat=3,  lng=3}, Object { lat=3,  lng=3}, Object { lat=3,  lng=3}]

但如果我尝试不带对象,它是可以的:

this.checkpoints = new Array();
this.checkpoints.push(1);
this.checkpoints.push(2);
this.checkpoints.push(3);
console.log(this.checkpoints);

结果是:

[1, 2, 3]

请问,我错过了什么?提前感谢!

因为您只是更改了同一对象的属性值。你需要创建3个不同的对象。

你可以使用对象初始化器

来简化它
this.checkpoints = new Array();
this.checkpoints.push({
    lat: 1,
    lng: 1
});
this.checkpoints.push({
    lat: 2,
    lng: 2
});
this.checkpoints.push({
    lat: 3,
    lng: 3
});
console.log(this.checkpoints);

this.checkpoint = new Object();
    this.checkpoint['lat'];
    this.checkpoint['lng'];
this.checkpoint['lat'] = 1;
this.checkpoint['lng'] = 1;
this.checkpoints.push(this.checkpoint);
this.checkpoint['lat'] = 2;
this.checkpoint['lng'] = 2;
this.checkpoints.push(this.checkpoint);
this.checkpoint['lat'] = 3;
this.checkpoint['lng'] = 3;
this.checkpoints.push(this.checkpoint);
它只改变checkpoint['lat'], checkpoint['lng']的属性所以当你执行

" console.log(this.检查点);"语句

它将只显示最后一次更改的属性值,并且对于['lat']和['lng']先前的值都被最后一个值覆盖。