0

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

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
RONE
  • 5,415
  • 9
  • 42
  • 71
  • possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Liam Mar 23 '15 at 17:27

3 Answers3

1

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.

Nate
  • 18,752
  • 8
  • 48
  • 54
1

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));
hamed
  • 7,939
  • 15
  • 60
  • 114
0

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.

FunkyKnuck
  • 36
  • 3