1. 程式人生 > >JS 陣列按指定長度切割,返回一個新的陣列集合,比如按照3的倍數切割,返回結果為每三個一組

JS 陣列按指定長度切割,返回一個新的陣列集合,比如按照3的倍數切割,返回結果為每三個一組

let data = [
    {name:'小趙',value:'12'},
    {name:'小錢',value:'12'},
    {name:'小孫',value:'12'},
    {name:'小李',value:'12'},
    {name:'小周',value:'12'},
    {name:'小吳',value:'12'},
    {name:'小鄭',value:'12'},
    {name:'小王',value:'12'},
    {name:'小付',value:'12'},
    {name:'小張',value:'12'}
]
console.log(data);
let FunData = (e)=>{
    let proportion = 3; //按照比例切割
    let num = 0;
    let _data =[];
    for(let i=0;i<e.length;i++){
        if(i % proportion == 0 && i != 0){
            _data.push(e.slice(num,i));
            num = i;
        }
        if((i+1)==e.length){
            _data.push(e.slice(num,(i+1)));
        }
    }
    return _data;
}
console.log(FunData(data));

看一下輸出結果