简体   繁体   中英

Object Behavior is not understood

I have been working with JavaScript for quite a time, but have never encountered this issue:

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

In the first example, you have one (only one) object, obj . You are creating an array of 3 (not 5) objects, but each position in your array refers to the same object .

When you set obj.id , you are changing it for the one and only object, which is referenced at each position in the array.

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. You're just editing the current obj defined outside the for loop. 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.

Inside the for loop, I just added 'var' so obj is a new one, not the same one that is in the parent scope:

var obj.id = i;

But you may want to reformat it a bit better than that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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