For loop in multidimensional javascript array

前端 未结 8 1497
我在风中等你
我在风中等你 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:07

    JavaScript does not have such declarations. It would be:

    var cubes = ...
    

    regardless

    But you can do:

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

    Note that JavaScript allows jagged arrays, like:

    [
      [1, 2, 3],
      [1, 2, 3, 4]
    ]
    

    since arrays can contain any type of object, including an array of arbitrary length.

    As noted by MDC:

    "for..in should not be used to iterate over an Array where index order is important"

    If you use your original syntax, there is no guarantee the elements will be visited in numeric order.

提交回复
热议问题