简体   繁体   English

如何更新多维数组中的元素

[英]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: 但这也改变了cells[1][0] ,结果是:

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

How do I only change cells[0][0] ? 如何只更改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. 当执行cells.push(row) ,您不会创建将被推送到cells的新数组,而是通过引用传递了该数组。

There is now only one array row = ["foo", "foo"] , referenced twice by the cells object. 现在只有一个数组row = ["foo", "foo"] ,由cells对象引用两次。 By doing cells[0][0] = "bar" , I would change the first element of the row object. 通过执行cells[0][0] = "bar" ,我将更改row对象的第一个元素。 Since the same object is referenced inside of the cells object twice, it will be the same on both positions. 由于同一对象在cells对象内部被两次引用,因此在两个位置上都是相同的。

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 . 对于克隆阵列的选择,请查看此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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