简体   繁体   中英

Creating an Array clone with spread operator, but it still has reference to original array

So I have these few lines of code:

  console.log(...cells);

  let testCells = [...cells];
  testCells[index].shape = selectedShape;
  testCells[index].player = player;

  console.log(...cells);

The interesting thing is that it is console.log() ing back the following.

在此处输入图像描述

I don't quite get it, why does cells change? There is no other part of the code that could interfere with cells . Any tips?

Full code available here.

It looks like even though you're spreading all the objects into the new array, it is still a reference to the old objects. You can break the reference by using JSON.stringify and JSON.parse to avoid any old unintended relationships.

 const cells = [ {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, {shape: 0, player: 0}, ]; console.log(...cells); const breakRef = obj => JSON.parse(JSON.stringify(obj)); let testCells = breakRef(cells); testCells[0].shape = 1; testCells[0].player = 0; console.log(...cells);

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