javascript - 使用 new Array().fill(0) 创建二维数组错误?

标签 javascript arrays

我想创建一个二维数组,但我发现了一个有趣的行为

const column = 10;
const row = 10;

let matrix = new Array(row).fill(new Array(column).fill(0));

matrix[0][1] = 1;

console.log(matrix)

令我惊讶的是,我得到的结果如下:

0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 

整个列号 1 设置为 1,我可以知道为什么会出现此行为吗?

最佳答案

Array#fill 方法填充相同的数组,其元素是对单个数组的引用。因此,您需要创建单独的数组作为元素。因此,更新一个数组将反射(reflect)所有其他数组,因为它们不是不同的数组,而是相同的。

使用 Array.from() 您可以通过 map function 来创造和产生值(value).

const column = 10;
const row = 10;

let matrix = Array.from({
  // create array of length `row`
  length: row 
  // map function to generate values
}, () => new Array(column).fill(0));

matrix[0][1] = 1;

console.log(matrix)

关于javascript - 使用 new Array().fill(0) 创建二维数组错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38760956/

相关文章:

php - URL 的 Jquery/Javascript 检索不起作用

javascript - 如果 videopsphere 加载,Aframe 启动画面

c++ - 示例程序崩溃

javascript - ASP.NET MVC - Javascript 数组总是作为 null 传递给 Controller

arrays - 如何从两个列表中快速打印

c - 将 2D 数组存储在 3D 数组中

javascript - 升级到 SItecore 9 后不加载 Css 和 Js 文件

javascript - 如何将JavaScript代码封装为jQuery插件或其他解决方案

javascript - 在 Google Maps API V3 中复制标记图标

java - Java ArrayList 真的比 C++ vector 慢这么多吗?