推入数组后变量值发生变化 [英] Variable value changes after pushing in array

查看:49
本文介绍了推入数组后变量值发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在测试这种代码的小巧性:

So I was testing this little peace of code:

<script>
  var newData = {}, graphs = []
  for(var j=0; j<2; j++){
    newData["name"] = 'value '+ j
    console.log(newData["name"]);
    graphs.push(newData);
    console.log(graphs);
  }
</script>

我在网络控制台中有以下输出:

I've got the following output in the webconsole:

value 0 
Array [ Object ] 
value 1 
Array [ Object, Object ]

数组中的所有对象具有完全相同的值:

All Objects in the Arrays have the exact same Values:

name:"value 1"

我真的为此感到挣扎,因为我没有更改任何值,并且名称仍在同一循环中更改.

I am really struggling with this because I don't change any values and the name is still changed in the same loop.

非常感谢您的回答!

推荐答案

在javascript中将对象放入数组意味着您要对该数组中的对象而不是引用 >该对象的值.在您的示例中,创建一个对象newData,然后在循环中更改该对象的name属性.这意味着在循环结束时,您将剩下一个newData对象和{'name': 'value 2'}

Putting an object into an array in javascript means you're putting a reference to that object in the array rather than the value of that object. In your example, you create a single object, newData and you change the name property on that object in your loop. That means that at the end of the loop you're left with a newData object with {'name': 'value 2'}

当您查看graphs[0]时,它将告诉您它包含对newData的引用,该引用类似于{'name': 'value 2'}. graphs[1]

When you then take a look at graphs[0], it will tell you that it contains a reference to newData which looks like {'name': 'value 2'}. The same holds for graphs[1]

您可以通过每次在数组中创建一个新对象来解决此问题,例如:

you can solve this by making a new object each time in your array as such:

graphs = []
for(var j=0; j<2; j++){
  var newData = {}
  newData["name"] = 'value '+ j
  console.log(newData["name"]);
  graphs.push(newData);
  console.log(graphs);
}

这篇关于推入数组后变量值发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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