JS 数组按指定长度切割,返回一个新的数组集合,比如按照3的倍数

2020-09-22  本文已影响0人  秀萝卜

JS 数组按指定长度切割,返回一个新的数组集合,比如按照3的倍数切割,返回结果为每三个一组

<html>
<script>
    function arraySlice(array, sliceNum) {
        var newArray = [];
        let viod = 0;//数组初始量
        for (let i = 0; i < array.length; i++) {
            if (i % sliceNum == 0 && i != 0) {
                newArray.push(array.slice(viod, i));
                viod = i;
            }
            if (i + 1 == array.length) {
                newArray.push(array.slice(viod, i + 1));
            }
        }
        return newArray;
    }
    var array = [
        { name: "1", },
        { name: "2", },
        { name: "3", },
        { name: "4", },
        { name: "5", },
        { name: "6", },
        { name: "7", },
        { name: "8", },
        { name: "9", },
        { name: "10", },
        { name: "9", },
        { name: "10", },
    ]
    var newArray = arraySlice(array, 3);
    console.log(newArray);
</script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读