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