更改一个数组元素会影响其他元素 [英] Changing one array element affects other elements

查看:115
本文介绍了更改一个数组元素会影响其他元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的javascript代码.

I have a javascript code as below.

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.有人可以告诉此代码有什么问题吗?

My issue is, when I change one element state[0][3] = 2; it affects all rows. All rows 3rd index value becomes 2. Can someone tell what is wrong in this code?

推荐答案

有人可以告诉我这段代码有什么问题吗?

Can someone tell what is wrong in this code?

您正在使用一个 row数组存储全部state中的条目. fill接受您提供的 value 并将该值重复放入目标数组中.您提供的值是对您创建的单个数组的引用,因此这些条目的 all 最终都引用了 same 行,如下所示:

You're using one row array for all your entries in state. fill takes the value you give it and puts that value in the target array repeatedly. The value you're giving it is a reference to the single array you've created, so all of those entries end up referring to the same row, like this:


                                          +−−−−−−−−−+
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       |−−−−−−−−−−−−−−−−−+
          +−−−−−−−−−+

您需要为state中的每个插槽创建一个新的行数组:

You'll need to create a new row array for each slot in state:

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

.as-console-wrapper {
  max-height: 100% !important;
}

...或仅具有ES5中的功能:

...or with only features present in ES5:

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

.as-console-wrapper {
  max-height: 100% !important;
}

这篇关于更改一个数组元素会影响其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆