更改一个数组元素会影响其他元素 [英] Changing one array element affects other elements
问题描述
我有一个 javascript 代码,如下所示.
var row = new Array(7);row.fill(0);var state = new Array(7);状态.填充(行);状态[0][3] = 2;console.log(state);
我的问题是,当我更改一个元素 state[0][3] = 2;
它会影响所有行.所有行的第 3 个索引值变为 2.有人能说出这段代码有什么问题吗?
有人能说出这段代码有什么问题吗?
您正在将one row
数组用于所有 state
中的条目.fill
获取您给它的 value 并将该值重复放入目标数组中.您给它的值是对您创建的单个数组的引用,因此所有这些条目最终会引用相同行,如下所示:
您需要为 state
中的 每个 槽创建一个新的行数组:
let state = Array.from({length:7}, () => {返回新数组(7).填充(0);});状态[0][3] = 2;console.log(state);
.as-console-wrapper {最大高度:100%!重要;}
...或者只有 ES5 中存在的特性:
var state = [0,0,0,0,0,0,0].map(function() {返回 [0,0,0,0,0,0,0];});状态[0][3] = 2;console.log(state);
.as-console-wrapper {最大高度:100%!重要;}
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);
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?
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 |−−−−−−−−−−−−−−−−−+ +−−−−−−−−−+
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;
}
...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屋!