JavaScript代码怪异的行为与阵列 [英] weird behaviour of javascript with arrays

查看:94
本文介绍了JavaScript代码怪异的行为与阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看下面的JavaScript片段

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

我很惊讶地看到输出为 [对象{名=你},{对象名称=你}]

由于我们正在推动的引用,都必须指向同一个对象。但至少后的第一个推输出必须像对象{名称=我}

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"}

这究竟是为什么?

感谢:)

推荐答案

与Chrome的控制台的问题是,它不会复制您传递给它的对象。

The problem with Chrome's console is that it doesn't copy the objects you pass to it.

到时候Chrome的构建控制台显示它已经改变了对象。

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

和期待的数组中,在不到3秒。

and look inside the array in less than 3 seconds.

小提琴: http://jsfiddle.net/TMDq2/

有些人可能会认为这是一个错误,有些优化。它至少一个边缘实施...

Some may see it as a bug, some as an optimization. It's at least a borderline implementation...

这篇关于JavaScript代码怪异的行为与阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆