[英]Why does assigning an object a value to that of another object, and then reassigning the original object change both objects?
I was performing some calculations on the following array of objects:我正在对以下对象数组执行一些计算:
array = [ { x: 6, y: 2 }, { x: 7, y: 2 }, { x: 8, y: 2 } ]
At each iteration, I set each objects equal to it's adjacent except the one at index 0.在每次迭代中,我将每个对象设置为与其相邻的对象相同,但索引为 0 的对象除外。
for (let i = array.length - 1; i > 0; i--) {
array[i] = array[i-1]
}
And got the following answer:并得到以下答案:
[ { x: 6, y: 2 }, { x: 6, y: 2 }, { x: 7, y: 2 } ]
Then I set the object at index 0 like so array[0].x = 5
, and got:然后我将 object 设置在索引 0 处,就像
array[0].x = 5
一样,得到:
[ { x: 5, y: 2 }, { x: 5, y: 2 }, { x: 7, y: 2 } ]
My assumption would've been that the object at index 1 would not have been changed as well.我的假设是索引 1 处的 object 也不会改变。 Why is this?
为什么是这样?
That happens because you are assigning references instead of values:发生这种情况是因为您分配的是引用而不是值:
array[i] = array[i-1]
You can create a shallow copy of the object using, for example, Object.assign()
:您可以使用例如
Object.assign()
创建 object 的浅表副本:
array[i] = Object.assign({}, array[i-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.