JS数组分段

遍历原数组,截取子数组后组成新数组

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。