简体   繁体   中英

How to update elements in multi-dimensional array

Suppose I have the following array structure:

let cells = [
  ['foo', 'foo'],
  ['foo', 'foo']
]

And I want to update it so it becomes:

[
  ['bar', 'foo'],
  ['foo', 'foo']
]

I thought this would suffice:

cells[0][0] = 'bar';

But that changes cells[1][0] too, resulting instead in:

[
  ['bar', 'foo'],
  ['bar', 'foo']
]

How do I only change cells[0][0] ?

Sounds like in your program, you have an array with two attributes referencing the same object. This would happen in the following code:

let row = ["foo", "foo"]
let cells = [];
cells.push(row);
cells.push(row);

When you do cells.push(row) , you don't create a new array which will be pushed to cells , you instead pass the array by reference.

There is now only one array row = ["foo", "foo"] , referenced twice by the cells object. By doing cells[0][0] = "bar" , I would change the first element of the row object. Since the same object is referenced inside of the cells object twice, it will be the same on both positions.

Depending on your use case, you either want to clone the first array, or create a new array independently on the first array.

For your options of cloning the array, check out this question .

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