JS数组分段
2023-12-08 本文已影响0人
倪大头
遍历原数组,截取子数组后组成新数组
function splitList(list, range) {
let count = list.length
let startIndex = 0
let splitList = []
while(count > 0) {
let rangeLength = Math.min(range, count)
let subList = list.slice(startIndex, startIndex + rangeLength)
splitList.push(subList)
count -= rangeLength
startIndex += rangeLength
}
return splitList
}
使用:
let array = [1, 2, 3, 4, 5, 6, 7, 8]
let result = splitList(array, 3)
console.log(result)