How to create empty 2d array in javascript?
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:
const 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: ([https://youtu.be/tMeDkp1J2OM][2])
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 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.
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'
.