# For loop in multidimensional javascript array

42

Since now, I'm using this loop to iterate over the elements of an array, which works fine even if I put objects with various properties inside of it.

``````var cubes[];

for (i in cubes){
cubes[i].dimension
cubes[i].position_x
ecc..
}
``````

Now, let's suppose cubes[] is declared this way

``````var cubes[][];
``````

Can I do this in Javascript? How can I then automatically iterate in

``````cubes
cubes
cubes
cubes
cubes
cubes
cubes
ecc...
``````

As a workaround, I can just declare:

``````var cubes[];
var cubes1[];
``````

and work separately with the two arrays. Is this a better solution?

This question is tagged with `javascript` `loops` `multidimensional-array`

~ Asked on 2012-04-05 02:22:11

### The Best Answer is

61

You can do something like this:

``````var cubes = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

for(var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
for(var j = 0; j < cube.length; j++) {
display("cube[" + i + "][" + j + "] = " + cube[j]);
}
}
``````

Working jsFiddle:

The output of the above:

``````cube = 1
cube = 2
cube = 3
cube = 4
cube = 5
cube = 6
cube = 7
cube = 8
cube = 9
``````

~ Answered on 2012-04-05 02:29:25

20

``````var cubes = [["string", "string"], ["string", "string"]];

for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
``````

~ Answered on 2012-04-05 02:25:40