For loop in multidimensional javascript array

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

    An efficient way to loop over an Array is the built-in array method .map()

    For a 1-dimensional array it would look like this:

    function HandleOneElement( Cuby ) {
       Cuby.dimension
       Cuby.position_x
       ...
    }
    cubes.map(HandleOneElement) ; // the map function will pass each element
    

    for 2-dimensional array:

    cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )
    

    for an n-dimensional array of any form:

    Function.prototype.ArrayFunction = function(param) {
      if (param instanceof Array) {
        return param.map( Function.prototype.ArrayFunction, this ) ;
      }
      else return (this)(param) ;
    }
    HandleOneElement.ArrayFunction(cubes) ;
    

提交回复
热议问题