问题:
编写一个函数, 把一个数组 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…