[英]Why does assigning an object a value to that of another object, and then reassigning the original object change both objects?
我正在對以下對象數組執行一些計算:
array = [ { x: 6, y: 2 }, { x: 7, y: 2 }, { x: 8, y: 2 } ]
在每次迭代中,我將每個對象設置為與其相鄰的對象相同,但索引為 0 的對象除外。
for (let i = array.length - 1; i > 0; i--) {
array[i] = array[i-1]
}
並得到以下答案:
[ { x: 6, y: 2 }, { x: 6, y: 2 }, { x: 7, y: 2 } ]
然后我將 object 設置在索引 0 處,就像array[0].x = 5
一樣,得到:
[ { x: 5, y: 2 }, { x: 5, y: 2 }, { x: 7, y: 2 } ]
我的假設是索引 1 處的 object 也不會改變。 為什么是這樣?
發生這種情況是因為您分配的是引用而不是值:
array[i] = array[i-1]
您可以使用例如Object.assign()
創建 object 的淺表副本:
array[i] = Object.assign({}, array[i-1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.