How to create empty 2d array in javascript?

后端 未结 8 1605
执笔经年
执笔经年 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'.

    0 讨论(0)
  • 2020-12-08 07:48

    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.

    0 讨论(0)
提交回复
热议问题