1

我有一个单维对象数组:

var myArray = [ { record  : "value" ,
                  recod2  : "value" ,
                  record3 : "value"
                } ,
                { record  : "value" ,
                  record2 : "value"
                  record3 : "value"
                } ,
                .
                .
                .
              ] ;

由此,我想构造一个锯齿状的二维数组(数组数组),如下所示:

var result = [ [ {} , {} , {} , {} ] ,
               [ {} , {} , {} , {} ] ,
               [ {} , {} , {} , {} ] ,
               .
               .
               .
             ] ;

例如,如果我的第一个数组包含 8 个对象,则结果数组应如下所示:

var result = [ [ obj1 , obj2 , obj3 , obj4 ] ,
               [ obj5 , obj6 , obj7 , obj8 ] ,
             ] ;

如何使用 for 循环实现这一点?

4

3 回答 3

2
var result = [], data = /* above object */;
for (var i = 0; i < data.length; i++){
  if (i % 4 == 0) result.push([]);
  result[Math.floor(i / 4)].push(data[i]);
}

应该做的伎俩。每第 4 个对象,我们就开始一个新的(嵌套)数组并向其中添加元素。

输出(假设 8 个元素):

[
  [
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"}
  ],
  [
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"},
    {"record": "value",
      "record2": "value",
      "record3": "value"}
  ]
]
于 2013-08-27T19:37:56.737 回答
1

你真的尝试过什么吗?一些显示您尝试的代码将不胜感激。然而...

您可以使用slice()javascript 的数组对象提供的方法:

func transform2d( srcArray , modulus )
{
    var result = undefined ;
    if ( modulus > 0 )
    {
      result = [] ;
      for ( var i = 0 ; i < srcArray.length ; i+= modulus )
      {
        result.push( srcArray.slice( i , i+modulus ) ) ;
      }
    }
    return result ;
}

您应该注意,如果您不介意在此过程中破坏源数组,也可以使用该splice()方法:

func transform2d( srcArray , modulus )
{
    var result = undefined ;
    if ( modulus > 0 )
    {
      result = [] ;
      while ( srcArray.length > 0 )
      {
        result.push( srcArray.splice( 0 , modulus ) ) ;
      }
    }
    return result ;
}

由于副作用,我认为这种splice()方法是……次优的。

显然,伟大的思想是一样的。另请参阅此答案:https ://stackoverflow.com/a/8495740/467473

于 2013-08-27T20:02:07.073 回答
0

使用一个简单的循环过冲,然后向后工作,删除多余的undefined

var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var result = [], i;
for (i = 0; i < myArray.length; i += 4) { // adding 4 each time
    result.push([myArray[i], myArray[i + 1], myArray[i + 2], myArray[i + 3]]);
}
// then if you have length !== 0 mod 4, work backwards
while ((i = result.length - 1) * 4 + result[i].length > myArray.length)
     result[i].pop(); // removing items from the end
// now you are left with
result; // [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
于 2013-08-27T19:46:23.980 回答