如何在javascript中添加一个对象到数组
How to append an object to array in javascript?
为什么数组只得到最后一个对象?
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']先前的值都被最后一个值覆盖。
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- 我想遍历一个对象数组,我不想要任何重复项
- 尝试在一个对象的值和一个对象数组之间进行匹配
- Mongoose模式:强制创建一个对象数组
- 可以't分配给一个对象数组javascript
- 如何在Javascript或jQuery中在一个对象数组中重复值
- 使用jQuery.ajax请求向PHP函数发送一个对象数组
- 如何将所有复选框放入一个对象数组并标记选中的复选框
- 循环遍历JQueryUI选项卡控件中的每个选项卡,并构建一个对象数组
- 用javascript将一个对象数组复制到另一个数组中(深度复制)
- 给定一个对象数组,创建一个函数,该函数返回一个 Object,该 Object 具有按类型分组的路径数组
- 如何存储一个对象数组,这些对象是 ajax 查询从 javascript 中的 JSON 中提取数据的结果
- 当我将一个对象链接到一个对象数组时,两个对象的值是如何链接的
- ng-repeat失败,并显示一个对象数组
- 我可以使用 Lodash 来“折叠”一个对象数组吗?
- 根据属性值 lodash 将属性从对象数组合并到另一个对象数组中
- JavaScript检查一个对象数组的结果是错误的,而它应该是真的
- 给定一个对象数组,找到具有特定键的对象