javascript 如何在javascript中创建空的二维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16512182/
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
How to create empty 2d array in javascript?
提问by meks
How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
如何在 Javascript 中创建一个空的二维数组(不知道新数组中有多少行或列)?
If it's a simple array var newArray = new Array();
I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1]
or myArray[0,1]
)?
如果它是一个简单的数组,var newArray = new Array();
我可以根据需要分配任意数量的元素。但是二维数组呢?我可以在不指定行数和列数的情况下创建一个吗?以及之后如何访问元素(myArray[0][1]
或myArray[0,1]
)?
采纳答案by Siamak A.Motlagh
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript.
Check out jsFiddle Live Demo
Define:
是的,您可以创建一个空数组,然后将数据推入其中。在 JavaScript 中不需要先定义长度。
查看jsFiddle Live Demo
定义:
var arr = [[],[]];
Push data:
推送数据:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
读取数据:
alert(arr[0][2]);
alert(arr[1][3]);
Update
更新
Here is also a video recommended by Brady Dowling:
Create a 2D array
这里还有一个Brady Dowling推荐的视频:
Create a 2D array
回答by André
You can create a 6 x 6 empty array like this:
您可以像这样创建一个 6 x 6 的空数组:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6)
generates an array with length = 6 and full ofundefined
values.- We map that array to another array full of
undefined
values. - In the end, we get a 6x6 grid full of
undefined
positions.
Array(6)
生成一个长度为 6 且充满undefined
值的数组。- 我们将该数组映射到另一个充满
undefined
值的数组。 - 最后,我们得到了一个 6x6 的充满
undefined
位置的网格。
If you need to initialize the grid with a default value:
如果您需要使用默认值初始化网格:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'
.
现在你有一个 6 x 6 的网格,充满了'foo'
.
回答by Guffa
There are no two dimensional arrays in Javascript.
Javascript 中没有二维数组。
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
要实现二维数组的效果,您可以使用数组数组,也称为锯齿数组(因为内部数组可以具有不同的长度)。
An empty jagged array is created just like any other empty array:
创建一个空的锯齿状数组就像任何其他空数组一样:
var myArray = new Array();
You can also use an empty array literal:
您还可以使用空数组文字:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
要将任何项目放入锯齿状数组中,您首先必须将内部数组放入其中,例如像这样:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
您还可以从一开始就创建一个包含许多空数组的数组:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
这为您提供了一个没有任何项目的锯齿状数组,但它由三个内部数组准备。
As it's an array of arrays, you access the items using myArray[0][1]
.
由于它是一个数组数组,因此您可以使用myArray[0][1]
.
回答by Noah Ellman
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
假设您想制作一个 100x100 的二维数组(即矩阵),您可以在一行中完成,如下所示:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's. Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
这将创建一个 100x100 的 NULL 矩阵。将 100x100 替换为您想要的任何尺寸,并将 null 替换为您首选的默认值,或者空白表示未定义。
回答by Qvcool
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
回答by Howard Brown
Two things:
两件事情:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
1) 如果在 var myArray = [[],[]]; 之后调用,数组长度属性会错误地报告数组长度;陈述。从技术上讲,由于定义了空数组,因此它们由 length 属性计算,但本着 length 属性的精神,它确实应该返回 0,因为没有将非空元素添加到任何数组中。
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
最小的解决方法是使用两个嵌套的 for(in) 循环,一个用于第一个数组,一个用于第二个数组,并计算未定义的元素。
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
2) 扩展 Siamak A.Motlagh 示例并添加 arr([2][4]) = 'Hi Mr.C'; 分配失败并出现“未捕获的类型错误:无法设置未定义的属性 '4'”错误。
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
见jsFiddle:http: //jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
这是该代码的副本:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
为什么第三个任务失败?[[],[]] 创建语句告诉它第一个数组对 0 和 1 有效,但对 2 无效,或者 2 和 3 对第二个数组有效,但对 4 无效?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
最重要的是,我将如何在一个数组中定义一个数组,该数组可以在第一个和第二个数组中保存日期对象。我正在使用 jQuery-UI DatePicker,它需要一个日期数组,就像在日期对象中一样,我已经将其扩展为使用第二个日期数组来包含包含时间的日期对象,以便我可以跟踪多个日期,并且每天多次。
Thanks.
谢谢。
回答by alexandros84
This also works as an expression:
这也可用作表达式:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
我不知道它与这里的其他答案在性能方面的表现如何,如果您有线索,请在评论中告诉我。
If you don't know the length of the array beforehand pls have in mind that you can use either push([])
, or splice()
if you want to push/remove/replace a new element in place of an existing one.
如果您事先不知道数组的长度,请记住,您可以使用push([])
,或者splice()
如果您想推送/删除/替换一个新元素来代替现有元素。
回答by Diep Truong
const grid = new Array(n).fill(new Array(n))