meks meks - 1 year ago 60
Javascript Question

How to create empty 2d array in javascript?

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 (

Answer Source

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


var arr = [[],[]];

Push data:

arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';

Read data: