How to create empty 2d array in javascript?

后端 未结 8 1636
执笔经年
执笔经年 2020-12-08 07:07

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 newArra

8条回答
  •  旧时难觅i
    2020-12-08 07:32

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

提交回复
热议问题