如何在 JavaScript 中创建一个由零组成的二维数组?
有没有一种简单的方法可以在 JavaScript 中以编程方式创建二维数组?
我不想要什么:
var array2D = [
[0,0,0],
[0,0,0],
[0,0,0]
]
Is there an easy way to programmatically create a 2d array in javascript?
What I don't want:
var array2D = [
[0,0,0],
[0,0,0],
[0,0,0]
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
2017 年解决方案:
虽然迟到了,但这篇文章在 Google 搜索结果中的排名仍然很高。
要创建给定大小的空二维数组(可适应更多维度):
预填充二维数组:
例如:
警告:
Array(rows).fill(Array(columns)) 将导致所有行都是对同一数组的引用!
2018 年 9 月 24 日更新(感谢 @Tyler):
另一种可能的方法是使用 Array.fill() 来应用地图函数。
例如:
基准:
https://jsperf.com/multi-Dimension-array -map-vs-fill/5
Solution 2017:
Late to the Party, but this Post is still high up in the Google search results.
To create an empty 2D-Array with given size (adaptable for more dimensions):
Prefilled 2D-Array:
E.g.:
Warning:
Array(rows).fill(Array(columns))
will result in all rows being the reference to the same array!!Update 24th September 2018 (thanks to @Tyler):
Another possible approach is to use
Array.fill()
to apply the map function.E.g.:
Benchmark:
https://jsperf.com/multi-dimensional-array-map-vs-fill/5
好吧,您可以编写一个辅助函数:
Bonus:处理任意数量的维度。
Well, you could write a helper function:
Bonus: handles any number of dimensions.
您可以使用以下函数创建二维零数组:
You can use the following function to create a 2D array of zeros:
对于初学者来说,这是一种简洁、易于理解的方法:
编辑:这是我的代码的解释。您创建一个数组
twoDArr
来保存二维数组或数组的数组。您使用外部 for 循环来创建子数组。然后使用内部 for 循环向子数组添加零。然后将子数组添加到外部数组twoDarr
中。然后,重复该过程,无论外部 for 循环指定多少次。当外部 for 循环完成时,返回二维数组。基本上,外部 for 循环创建行(子数组),而内部 for 循环创建列(子数组中的元素)。外部 for 循环告诉您通过重复块中的代码
x
次来创建x
行(子数组),内部 for 循环告诉您创建y
列(元素),方法是重复块中的代码y
次。A no-frills, easy-to-understand method for beginners:
Edit: Here's an explanation of my code. You create an array,
twoDArr
, to hold the 2d array, or array of arrays. You use the outer for loop to create subarrays. Then you use the inner for loop to add zeros to the subarray. Then you add the subarray to the outer array,twoDarr
. Then you repeat the process however many times the outer for loop specifies. When the outer for loop is finished, you return the 2d array.Basically, the outer for loop creates the rows (subarrays), while the inner for loop creates the columns (elements in the subarrays). The outer for loop tells you to create
x
rows (subarrays) by repeating the code in the blockx
times, and the inner for loop tells you to createy
columns (elements) by repeating the code in the blocky
times.