Skip to content Skip to sidebar Skip to footer

Create Multidimensional Array By Using Javascript

This is a very strange to me actually. I can't figure out how create a multidimensional array dynamically. I want to create a three-level drop-down list, so I think I need a three

Solution 1:

If your only problem is creating the three-dimensional array, this should work:

var aCourse = [];

for(var i = 0; i < dimensionOneSize; i++) {
  aCourse[i] = [];
  for(var k = 0; k < dimensionTwoSize; k++)
    aCourse[i][k] = [];
}

It is good to note that JavaScript supports the short-hand definition of an array with square brackets [], so you can use those to make the dynamic definition cleaner.

Possibly Shorter

Also, I'm not sure if this works very well, but it might:

var aCourse = [[[]]];

So far, my testing has not proven a way to use this, but it does validate as a proper script.

Solution 2:

First, it's always good to initialize arrays using square brackets, []:

var aCourse = [];

And to simulate multidimensional arrays in JS, which is essentially an indeterminate number of arrays inside of a single array, do this:

aCourse[0] = [];

Or you could create the arrays inside of the square brackets when creating the array:

var aCourse = [
    [], [], []
];

This is equivalent to:

aCourse[0] = [];
aCourse[1] = [];
aCourse[2] = [];

Post a Comment for "Create Multidimensional Array By Using Javascript"