简体   繁体   中英

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.

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:

[ { 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. 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() :

array[i] = Object.assign({}, array[i-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM