欢迎加QQ交流:
2
0
2
3

JS将某个数组分割为N个对象一组(如,两两一组,三三一组等)

方法一:

var result = [];

var data = [

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

  {name:'chen',age:'25'},

]

for(var i=0;i<data.length;i+=3){

    result.push(data.slice(i,i+3));

}

  //[

//[{name:'chen',age:'25'},{name:'chen',age:'25'},{name:'chen',age:'25'}],

//[{name:'chen',age:'25'},{name:'chen',age:'25'},{name:'chen',age:'25'}],

//[{name:'chen',age:'25'},{name:'chen',age:'25'},{name:'chen',age:'25'}],

//[{name:'chen',age:'25'}],

  //]

方法二:

var spArray = function(N,Q){

var R = [],F;

for (F = 0;F < Q.length;) {

R.push(Q.slice(F,F += N))

}

return R

}

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];

console.log(spArray(5,arr))//[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14]]

 

原文链接:https://blog.csdn.net/qq_43156398/article/details/90715915

 

posted @ 2021-07-05 11:15  常安·  阅读(1213)  评论(0编辑  收藏  举报