在javascript中初始化和填充多维数组 [英] Initializing and filling multi dimension array in javascript
问题描述
我们如何初始化和创建新的多维数组?
How do we initialize and create new multi dimension array?
让我们想象一下我是否要初始化一个4x4多维数组并用0填充它
Let's imagine if I want to initialize a 4x4 multi dimension array and fill it with 0's
理想情况下,在2D数组中,我们会这样做
Ideally, in 2D arrays, we would do
让oned_array = new Array(10)。 fill(0);
//将创建大小为10的数组并用0填充它
let oned_array = new Array(10).fill(0);
// would create array of size 10 and fill it up with 0
我如何做[[0 ,0],[0,0]](2x2矩阵)
How would I do something like [[0,0], [0,0]] (2x2 matrix)
let matrix = new Array([]).fill(0);
我正在尝试解决一些算法问题,这需要我创建一个新的多维数组并继续通过他们(岛屿问题等)
I'm trying to solve few algorithm problems and this requires me creating a new multi dimension array and going through them (Island problem etc)
请告知。
编辑:
我找到的另一个解决方案:
Another solution I found:
数组(2).fill(0).map(_ =>数组(2).fill(0));
推荐答案
要获得一个独立的填充数组,你可以使用 数组。从
并映射一个带有映射值的新数组。
To get an independent filled array, you could use Array.from
and map a new array with mapped values.
var array = Array.from({ length: 4 }, _ => Array.from({ length: 4 }, _ => 4));
array[0][0] = 0;
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于在javascript中初始化和填充多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!