【发布时间】:2014-04-11 09:35:21
【问题描述】:
我已经创建了这个jsfiddle,但我无法解释为什么以下不会产生一个包含 5 个对象的数组,这些对象都具有不同的 id 属性:
var arr = ["1", "2", "3", "4", "5"];
var clone = {"id": "0", "name":"Matthew"};
var arrObj = [];
var idArr = [];
while((a=arr.pop()) != null){
clone.id = a;
console.log(clone);
arrObj.push(clone);
}
console.log(arrObj);
我最终在控制台中得到以下内容:
Object {id: "5", name: "Matthew"} (index):28
Object {id: "4", name: "Matthew"} (index):28
Object {id: "3", name: "Matthew"} (index):28
Object {id: "2", name: "Matthew"} (index):28
Object {id: "1", name: "Matthew"} (index):28
[Object, Object, Object, Object, Object]
当我打开 5 个克隆对象中的每一个时,它们的“id”值都为“1”
这是为什么?
【问题讨论】:
-
对象是通过引用传递的,你一遍又一遍地引用同一个对象。你需要克隆它。 stackoverflow.com/questions/122102/…
-
你引用的好帖子!我永远不会找到我的答案,因为那篇文章的标题和标签如此模糊。此外,这个问题解决了在循环外引用对象并以上述方式为它们分配值的注意事项。为类似的问题带来不同的视角,但不完全是重复的。
标签: javascript arrays object while-loop