For loop in multidimensional javascript array
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[0][0] = 1cube[0][1] = 2cube[0][2] = 3cube[1][0] = 4cube[1][1] = 5cube[1][2] = 6cube[2][0] = 7cube[2][1] = 8cube[2][2] = 9
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]); }}
A bit too late, but this solution is nice and neat
const arr = [[1,2,3],[4,5,6],[7,8,9,10]]for (let i of arr) { for (let j of i) { console.log(j) //Should log numbers from 1 to 10 }}
Or in your case:
const arr = [[1,2,3],[4,5,6],[7,8,9]]for (let [d1, d2, d3] of arr) { console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9}
Note: for ... of
loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)
Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach()
, for...in
, for...of
and traditional for()
. It depends on your case to decide which one to use. (ES6 also has .map()
, .filter()
, .find()
, .reduce()
)