我需要创建一个数组的数组。每个嵌套数组都应该用零填充。我试过这个:
let test = Array
.from(
new Array(8)
.fill(
new Array(8).fill(0)
)
);
但后来我遇到了引用问题。例如,如果我这样做:
test[1][2] = 1;
那么每个嵌套数组都有值 1
在索引2
:
console.log(test[2][2]) // 1
我想出了使用循环的简单解决方案:
const testArray = new Array(8);
for (let i = 0; i < testArray.length; i++) {
testArray[i] = new Array(8).fill(0);
}
现在它可以工作了,并且引用没有问题。但我不明白为什么第一次尝试时会出现这个问题。有哪位好心人可以向我解释一下吗?
最佳答案
您将使用对单个数组的 8 个相同引用来填充数组,而不是使用对 8 个单独数组的 8 个不同引用来填充该数组。 fill
为其填充的数组中的每个条目重用相同的值,因此您会得到:
+−−−−−−−−−−−−+ | (array) | +−−−−−−−−−−−−+ +−−−−−−−−−+ | 0: Ref2215 |−−−−−−−−+−+−+−+−+−+−+−−−−−>| (array) | | 1: Ref2215 |−−−−−−−/ / / / / / / +−−−−−−−−−+ | 2: Ref2215 |−−−−−−−−/ / / / / / | 0: 0 | | 3: Ref2215 |−−−−−−−−−/ / / / / | 1: 0 | | 4: Ref2215 |−−−−−−−−−−/ / / / | 2: 0 | | 5: Ref2215 |−−−−−−−−−−−/ / / | ... | | 6: Ref2215 |−−−−−−−−−−−−/ / +−−−−−−−−−+ | 7: Ref2215 |−−−−−−−−−−−−−+ +−−−−−−−−−−−−+
It doesn't matter which array slot you use, they all contain a reference to the same one array.
Your second code block creates separate arrays (I won't bother with the diagram :-)). Here's a slightly shorter way to do it:
let test = Array.from(
Array(8),
() => new Array(8).fill(0) // Mapping callback creates
); // new array for every entry
// in the outer array
关于javascript - 使用数组构造函数创建的嵌套数组 - 引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48370608/