如何在javascript中将对象附加到数组中?

如何在javascript中将对象附加到数组中?,javascript,object,Javascript,Object,为什么数组只获取最后一个对象 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[

为什么数组只获取最后一个对象

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.checkpoint=新对象();
这个检查点['lat'];
这个检查站['lng'];
检查点['lat']=1;
这个检查点['lng']=1;
this.checkpoints.push(this.checkpoint);
这个检查点['lat']=2;
这个检查点['lng']=2;
this.checkpoints.push(this.checkpoint);
这个检查点['lat']=3;
这个检查点['lng']=3;

this.checkpoints.push(this.checkpoint)这是因为推送是基于引用的。它推送
this.checkpoint
的地址(参考),而不是它的值。我想知道这是什么:
this.checkpoint['lat'];这个检查站['lng']do@RoyiNamir这意味着您正在为具有这些名称的对象分配属性。@RaeenHashemi这不是一个问题,而是指向一个非代码:(OP代码的第3行和第4行)
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);