简体   繁体   English

不了解对象行为

[英]Object Behavior is not understood

I have been working with JavaScript for quite a time, but have never encountered this issue: 我使用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":""}]

Maybe I have miss understood the objects here. 也许我想念这里的对象。 can you please tell me why is this behavior. 您能告诉我为什么会这样吗?

I have a jsfiddle.net Fiddle 我有一个jsfiddle.net 小提琴

In the first example, you have one (only one) object, obj . 在第一个示例中,您有一个(只有一个)对象obj You are creating an array of 3 (not 5) objects, but each position in your array refers to the same object . 您要创建一个由3个(而不是5个)对象组成的数组,但是数组中的每个位置都指向同一对象

When you set obj.id , you are changing it for the one and only object, which is referenced at each position in the array. 设置obj.id ,您将为一个唯一对象更改它,该对象在数组的每个位置都被引用。

In the second example, you are creating a new object each time: 在第二个示例中,您每次都创建一个新对象:

{"id": i, "name":''}          // this creates a new object

So it works. 这样就行了。

Try to use something like this: 尝试使用如下形式:

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));

You just need to create a new obj inside the first for loop. 您只需要在第一个for循环内创建一个新的obj。 You're just editing the current obj defined outside the for loop. 您只是在for循环外编辑当前定义的obj。 So each loops sets the id of the one obj to it's i value, then you're inserting a copy of that into the array, so on the next loop, each reference to the original object is changed. 因此,每个循环将一个obj的id设置为其i值,然后将其副本插入数组,因此在下一个循环中,对原始对象的每个引用都将更改。

Inside the for loop, I just added 'var' so obj is a new one, not the same one that is in the parent scope: 在for循环中,我刚刚添加了'var',所以obj是一个新变量,而不是父作用域中的同一个变量:

var obj.id = i;

But you may want to reformat it a bit better than that. 但是您可能想要重新格式化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM