美文网首页
JS数组分段

JS数组分段

作者: 倪大头 | 来源:发表于2023-12-08 16:19 被阅读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)
    

    相关文章

      网友评论

          本文标题:JS数组分段

          本文链接:https://www.haomeiwen.com/subject/wjrebdtx.html