I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?
var obj = {x:12};
var arr =[];
for(var i=0;i<5;i++){
obj["x"] = i;
arr.push(obj);
println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));
Output of the above code returns -
Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]
Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]