javascript - 使用数组构造函数创建的嵌套数组 - 引用问题

标签 javascript arrays

我需要创建一个数组的数组。每个嵌套数组都应该用零填充。我试过这个:

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/

相关文章:

javascript - SVG 重新排序 z-index(Raphael 可选)

javascript - 在文档正文中嵌入 Javascript?

javascript - 从不同的表单中选择一个标签

javascript - Ajax 调用后加载 jQuery 库

javascript - 如何在对象数组上使用 Array.prototype.map() 来根据它的值过滤掉一些特定的键?

javascript - 在性能受限的环境中缓存文本/图像资源

python - 将 3x32x32 大小的 numpy 图像数组转换为 32x32x3 并保存为 Python 中的实际图像

javascript - 使用javascript根据条件将数组分成两部分

c# - 数组大小超出寻址限制(C# 与 C++)

javascript - Array.map() "syntax Error"in IE11,映射多个JSON Object字段