Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird behaviour of javascript with arrays

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 :)

like image 611
Navaneeth Avatar asked Dec 07 '12 16:12

Navaneeth


1 Answers

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...

like image 124
Denys Séguret Avatar answered Oct 01 '22 20:10

Denys Séguret