Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in multidimensional javascript array

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[0][0] cubes[0][1] cubes[0][2] cubes[1][0] cubes[1][1] cubes[1][2] cubes[2][0] ecc... 

As a workaround, I can just declare:

var cubes[]; var cubes1[]; 

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

like image 992
Saturnix Avatar asked Apr 05 '12 02:04

Saturnix


People also ask

How do you loop through a multidimensional array?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

What is multidimensional array in JavaScript?

A multidimensional array is an array that contains another array. For example, // multidimensional array const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];

Are there multidimensional arrays in JavaScript?

JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.

How do you make a 3 by 3 matrix in JavaScript?

If you just use below method to create a 3x3 matrix. Array(3). fill(Array(3). fill(0));


1 Answers

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:

  • http://jsfiddle.net/TRR4n/

The output of the above:

cube[0][0] = 1 cube[0][1] = 2 cube[0][2] = 3 cube[1][0] = 4 cube[1][1] = 5 cube[1][2] = 6 cube[2][0] = 7 cube[2][1] = 8 cube[2][2] = 9 
like image 63
icyrock.com Avatar answered Sep 17 '22 20:09

icyrock.com