我已经做了这个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”
为什么会这样?
答案 0 :(得分:4)
clone
是一个对象。在javascript中,对象通过引用传递,因此您不会在每个索引中传递不同的对象。
这是可以工作的东西
while((a=arr.pop()) != null){
var clone = {"id": a, "name":"Matthew"};
clone.id = a;
arrObj.push(clone);
}
console.log(arrObj);
结果:
Array [
Object {id: "5", name: "Matthew"}
Object {id: "4", name: "Matthew"}
Object {id: "3", name: "Matthew"}
Object {id: "2", name: "Matthew"}
Object {id: "1", name: "Matthew"}
]
答案 1 :(得分:2)
JS中的对象是通过引用分配的。您需要复制它,例如jQuery.extend
。
var arr = ["1", "2", "3", "4", "5"];
var clone = {"id": "0", "name":"Matthew"};
var arrObj = [];
var idArr = [];
while((a=arr.pop()) != null){
clone = $.extend({}, clone);
clone.id = a;
console.log(clone);
arrObj.push(clone);
}
console.log(arrObj);
答案 2 :(得分:1)
如果你的克隆不包含任何功能,你可以这样做
while((a=arr.pop()) != null){
clone = JSON.parse(JSON.stringify(clone));
clone.id = a;
console.log(clone);
arrObj.push(clone);
}