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

Time:04-16

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.

enter image description here

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.

CodePudding user response:

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);

  • Related