Skip to content Skip to sidebar Skip to footer

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']

Solution 1:

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


Post a Comment for "Weird Behaviour Of Javascript With Arrays"