javascript 如何在javascript中创建一个二维零数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3689903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:57:22  来源:igfitidea点击:

How to create a 2d array of zeroes in javascript?

javascriptmultidimensional-array

提问by Travis

Is there an easy way to programmatically create a 2d array in javascript?

有没有一种简单的方法可以在 javascript 中以编程方式创建二维数组?

What I don't want:

我不想要的:

var array2D = [ 
  [0,0,0],
  [0,0,0],
  [0,0,0]
]

采纳答案by John Kugelman

Well, you could write a helper function:

好吧,你可以写一个辅助函数:

function zeros(dimensions) {
    var array = [];

    for (var i = 0; i < dimensions[0]; ++i) {
        array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
    }

    return array;
}

> zeros([5, 3]);
  [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Bonus: handles any number of dimensions.

奖励:处理任意数量的维度。

回答by FatalMerlin

Solution 2017:

解决方案 2017:

Late to the Party, but this Post is still high up in the Google search results.

晚会晚了,但这篇文章在谷歌搜索结果中仍然名列前茅。

To create an empty2D-Array with given size (adaptable for more dimensions):

要创建具有给定大小的2D 数组(适用于更多维度):

let array = Array(rows).fill().map(() => Array(columns));

Prefilled 2D-Array:

预填充二维阵列:

let array = Array(rows).fill().map(() => Array(columns).fill(0));

E.g.:

例如:

Array(2).fill().map(() => Array(3).fill(42));
// Result:
// [[42, 42, 42],
//  [42, 42, 42]]

Warning:

警告:

Array(rows).fill(Array(columns))will result in all rows being the reference to the same array!!

Array(rows).fill(Array(columns))将导致所有行都引用同一个数组!!



Update 24th September 2018 (thanks to @Tyler):

2018 年 9 月 24 日更新(感谢@Tyler):

Another possible approach is to use Array.fill()to apply the map function.

另一种可能的方法是使用Array.fill()map 函数。

E.g.:

例如:

Array.from(Array(2), _ => Array(3).fill(43));
// Result:
// [[43, 43, 43],
//  [43, 43, 43]]



Benchmark:

基准:

https://jsperf.com/multi-dimensional-array-map-vs-fill

https://jsperf.com/multi-dimensional-array-map-vs-fill

回答by MooGoo

function zero2D(rows, cols) {
  var array = [], row = [];
  while (cols--) row.push(0);
  while (rows--) array.push(row.slice());
  return array;
}

回答by Grant Miller

You can use the following function to create a 2D array of zeros:

您可以使用以下函数来创建二维数组

const zeros = (m, n) => [...Array(m)].map(e => Array(n).fill(0));

console.log(zeros(3, 4));

// [ [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ] ]