更改一个数组元素会影响其他元素

时间:2017-10-06 09:03:56

标签: javascript arrays

我有一个javascript代码如下。



var row = new Array(7);
row.fill(0);
var state = new Array(7);
state.fill(row);
state[0][3] = 2;
console.log(state);




我的问题是,当我更改一个元素state[0][3] = 2;时,它会影响所有行。所有行的第3个索引值变为2.有人可以告诉这段代码有什么问题吗?

1 个答案:

答案 0 :(得分:3)

  

有人能说出这段代码有什么问题吗?

您在<{1}}中使用一个 row数组来所有您的条目。 state获取您提供的并将该值重复放入目标数组中。您提供的价值是对您创建的单个数组的引用,因此所有条目最终都会引用相同的行,像这样:

                                          +−−−−−−−−−+
row−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−+−+−+−−>| (array) |
          +−−−−−−−−−+     | | | | | | |   +−−−−−−−−−+
state−−−−>| (array) |     | | | | | | |   | 0: 0    |
          +−−−−−−−−−+     | | | | | | |   | 1: 0    |
          | 0       |−−−−−+ | | | | | |   | 2: 0    |
          | 1       |−−−−−−−+ | | | | |   | 3: 0    |
          | 2       |−−−−−−−−−+ | | | |   | 4: 0    |
          | 3       |−−−−−−−−−−−+ | | |   | 5: 0    |
          | 4       |−−−−−−−−−−−−−+ | |   | 6: 0    |
          | 5       |−−−−−−−−−−−−−−−+ |   +−−−−−−−−−+
          | 6       |−−−−−−−−−−−−−−−−−+
          +−−−−−−−−−+

您需要为fill中的每个广告位创建一个新的行数组:

&#13;
&#13;
state
&#13;
let state = Array.from({length:7}, () => {
  return new Array(7).fill(0);
});
state[0][3] = 2;
console.log(state);
&#13;
&#13;
&#13;

...或仅包含ES5中的功能:

&#13;
&#13;
.as-console-wrapper {
  max-height: 100% !important;
}
&#13;
var state = [0,0,0,0,0,0,0].map(function() {
  return [0,0,0,0,0,0,0];
});
state[0][3] = 2;
console.log(state);
&#13;
&#13;
&#13;