Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  181] [ 6]  / answers: 1 / hits: 128124  / 11 Years ago, sun, may 12, 2013, 12:00:00

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 (myArray[0][1] or myArray[0,1])?


More From » javascript

 Answers
16

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://www.youtube.com/watch?v=tMeDkp1J2OM][2])
[#78275] Friday, May 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiley

Total Points: 733
Total Questions: 118
Total Answers: 94

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;