首页 > 代码库 > js将一维数组转化为二维数组

js将一维数组转化为二维数组

function reduceArray (arr,count) {
    var len,ar = Array(),k = 0;
    if (arr.length % count == 0) {
      len = parseInt(arr.length / count);
    } else{
      len = parseInt(arr.length / count) + 1;
    }
    for (var i = 0;i < len;i++) {
        if (ar[i]) {
            ar[i] = ar[i];
        }else{
            ar[i] = [];
        }
        for (var a = 0;a < count;a++) {
            ar[i][a] = arr[k];
            if (ar[i][a] == undefined) {
              ar[i].length = arr.length % count;
            }
            k++;    
        }
    }     
    var newAr = ar;
    console.log(newAr);
}
reduceArray([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],5) //[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15,][16,17,18,19,20],[21]]

js将一维数组转化为二维数组