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.