[英]Object Behavior is not understood
我使用JavaScript已经有一段时间了,但是从未遇到过这个问题:
var objArr = [];
var obj = {
id:null,
name:''
}
//Type 1: Why This do not work
//create an array of 5 object
for(var i=0; i<3; i++){
obj.id = i;
console.log(obj);
objArr.push(obj); //What is wrong here
}
console.log(JSON.stringify(objArr)); // Have 5 objects in the array, But if you see this object is display the last object
//output : [{"id":2,"name":""},{"id":2,"name":""},{"id":2,"name":""}]
//Type 2: Why This Works and why the above object works
var objArr=[];
//create an array of 5 object
for(var i=0; i<3; i++){
console.log(obj);
objArr.push({"id":i, "name":''});
}
console.log(JSON.stringify(objArr));
//output : [{"id":0,"name":""},{"id":1,"name":""},{"id":2,"name":""}]
也许我想念这里的对象。 您能告诉我为什么会这样吗?
我有一个jsfiddle.net 小提琴
在第一个示例中,您有一个(只有一个)对象obj
。 您要创建一个由3个(而不是5个)对象组成的数组,但是数组中的每个位置都指向同一对象 。
设置obj.id
,您将为一个唯一对象更改它,该对象在数组的每个位置都被引用。
在第二个示例中,您每次都创建一个新对象:
{"id": i, "name":''} // this creates a new object
这样就行了。
尝试使用如下形式:
var objArr=[];
for(var i=0; i<3; i++){
var obj = {};
obj['id'] = i;
obj['name'] = null;
console.log(obj);
objArr.push(obj);
}
console.log(JSON.stringify(objArr));
您只需要在第一个for循环内创建一个新的obj。 您只是在for循环外编辑当前定义的obj。 因此,每个循环将一个obj的id设置为其i值,然后将其副本插入数组,因此在下一个循环中,对原始对象的每个引用都将更改。
在for循环中,我刚刚添加了'var',所以obj是一个新变量,而不是父作用域中的同一个变量:
var obj.id = i;
但是您可能想要重新格式化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.