How to create empty 2d array in javascript?

2020-02-02 11:50发布

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?

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])?

标签: javascript
7条回答
别忘想泡老子
2楼-- · 2020-02-02 12:10

Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:

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.

查看更多
戒情不戒烟
3楼-- · 2020-02-02 12:12

There are no two dimensional arrays in 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].

查看更多
Root(大扎)
4楼-- · 2020-02-02 12:15

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.

查看更多
一夜七次
5楼-- · 2020-02-02 12:16

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.

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.

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.

See the 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?

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.

Thanks.

查看更多
时光不老,我们不散
6楼-- · 2020-02-02 12:25

You can create a 6 x 6 empty array like this:

var myGrid = [...Array(6)].map(e => Array(6));
  • Array(6) generates an array with length = 6 and full of undefined values.
  • We map that array to another array full of undefined values.
  • In the end, we get a 6x6 grid full of undefined positions.

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'.

查看更多
够拽才男人
7楼-- · 2020-02-02 12:30
var myArray = [
    ["cats","dogs","monkeys","horses"],
    ["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
查看更多
登录 后发表回答