1

问题:

编写一个函数,把一个数组arr按照指定的数组大小size分割成若干个数组块。

示例:

例如:chunk([1,2,3,4],2)=[[1,2],[3,4]];

chunk([1,2,3,4,5],2)=[[1,2],[3,4],[5]];

解答:

function chunk(arr, size) {
// Break it up.
    var diode = [];
    var count = Math.ceil(arr.length / size);
    var arrIndex = 0;
    var tempArrIndex = 0;
    for(var subArrTime = 0; subArrTime < count; subArrTime++){
        var subArray = new Array(size);
        tempArrIndex = arrIndex + size;
        for(var x = 0; arrIndex < tempArrIndex; arrIndex++,x++){
            if(arrIndex < arr.length){
                subArray[x] = arr[arrIndex];
            }
        }
        arrIndex = tempArrIndex;
        diode.push(subArray);
        
    }
    return diode;
    
    
}

chunk(["a", "b", "c", "d"], 2);

链接:

https://www.w3cschool.cn/code...


冒泡的马树
194 声望14 粉丝

曾痴迷于赛博朋克世界的代码玩家一枚,