How to create empty 2d array in javascript?

后端 未结 8 1641
执笔经年
执笔经年 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条回答
  •  天涯浪人
    2020-12-08 07:34

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

提交回复
热议问题