Let us consider the following JavaScript snippet
var arr = [];
function pushMe()
{
var temp = { "name": "me" };
arr.push(temp)
console.log(arr)
temp["name"] = "you";
arr.push(temp)
console.log(arr)
}
I was astonished to see the output as [Object { name="you"},Object { name="you"}]
As we are pushing the references, both must refer to same object. But at least after the first push output must be like Object { name="me"}
Why is this happening??
thanks :)
The problem with Chrome's console is that it doesn't copy the objects you pass to it.
By the time Chrome builds the console the objects it displays have changed.
If you want to see your "me", try this :
var arr = [];
var temp = { "name": "me" };
arr.push(temp)
console.log(arr)
setTimeout(function(){
temp["name"] = "you";
arr.push(temp)
console.log(arr)
}, 3000);
and look inside the array in less than 3 seconds.
Fiddle : http://jsfiddle.net/TMDq2/
Some may see it as a bug, some as an optimization. It's at least a borderline implementation...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With