使用新的Array()。fill(0)错误创建2D数组? [英] Create 2D array using new Array().fill(0) bug?

查看:229
本文介绍了使用新的Array()。fill(0)错误创建2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a 2d array, but i found an interesting behavior

const column = 10;
const row = 10;

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

matrix[0][1] = 1;

console.log(matrix)

令我惊讶的是结果如下:

and to my surprise i get the result as below:

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,请问我为什么会收到这种行为?

the entire column number 1 is set to 1, may I know why am I getting this behavior?

推荐答案

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

The Array#fill method filling with the same array that the elements are the reference to a single array. So you need to create separate arrays as elements. So updating one will reflect all other since they are not different array they are the same.

使用 Array.from() ,您可以通过创建并生成值映射函数

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)

这篇关于使用新的Array()。fill(0)错误创建2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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