weird behaviour of javascript with arrays

后端 未结 1 744
执念已碎
执念已碎 2021-01-13 04:54

Let us consider the following JavaScript snippet

var arr = [];
function pushMe()
{
      var temp = { \"name\": \"me\" };
      arr.push(temp)
      console.         


        
相关标签:
1条回答
  • 2021-01-13 05:18

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

    0 讨论(0)
提交回复
热议问题