1、split()方法 和 for 循环
function sliceArr(arr, split_len) {
// arr: 待拆分数组 ; split_len: 拆分长度
const res: any = []
for (let i = 0; i < arr.length; i += split_len) {
const chunk = arr.slice(i, i + split_len)
res.push(chunk)
}
return res
}
const arr = [1,2,3,4,5,6,7,8,9]
console.log(sliceArr(arr, 2)) // [ [1,2] , [3,4] , [5,6] , [7,8] , [ 9 ]
2、splice()方法 和 while (splice方法会改变原数组,不推荐!!!)
function spliceArr(arr , length){
const res = [];
while (arr.length > 0) {
const chunk = arr.splice(0, chunkSize);
res.push(chunk);
}
return res;
}
const arr = [1,2,3,4,5,6,7,8,9]
console.log(spliceArr(arr, 3)) // [ [1,2,3] , [4,5,6] , [7,8,9] ]