For loop in multidimensional javascript array

前端 未结 8 1504
我在风中等你
我在风中等你 2020-11-28 21:28

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 cu         


        
8条回答
  •  再見小時候
    2020-11-28 22:00

    Or you can do this alternatively with "forEach()":

    var cubes = [
     [1, 2, 3],
     [4, 5, 6],    
     [7, 8, 9],
    ];
    
    cubes.forEach(function each(item) {
      if (Array.isArray(item)) {
        // If is array, continue repeat loop
        item.forEach(each);
      } else {
        console.log(item);
      }
    });
    

    If you need array's index, please try this code:

    var i = 0; j = 0;
    
    cubes.forEach(function each(item) {
      if (Array.isArray(item)) {
        // If is array, continue repeat loop
        item.forEach(each);
        i++;
        j = 0;
      } else {
        console.log("[" + i + "][" + j + "] = " + item);
        j++;
      }
    });
    

    And the result will look like this:

    [0][0] = 1
    [0][1] = 2
    [0][2] = 3
    [1][0] = 4
    [1][1] = 5
    [1][2] = 6
    [2][0] = 7
    [2][1] = 8
    [2][2] = 9
    

提交回复
热议问题