方法一:
function group(array, subGroupLength) { let index = 0; let newArray = []; while(index < array.length) { newArray.push(array.slice(index, index += subGroupLength)); } return newArray; } 2,例如: var Array = [1,2,3,4,5,6,7,8,9,10,11,12];; var groupedArray = group(Array, 6); 得到的groupedArray 数组为: groupedArray[[1,2,3,4,5,6],[7,8,9,10,11,12]]
二,上面分割出的数组是等长的,但是某些情况下,最后一个数组的长度会少于正常的长度,于是需要判断如果分割出来的数组,小于规定长度,则添加空对象,补齐数组长度:
function group(array, subGroupLength) { let index = 0; let newArray = []; while(index < array.length) { console.log(index) var childArr=array.slice(index, index += subGroupLength); if(childArr.length<subGroupLength){ var len=subGroupLength-childArr.length; for(let i=0;i<len;i++){ childArr.push({}); } } newArray.push(childArr); } return newArray; } var arr=[1,2,3,4,5,6,7,8,9,0,11,12,13]; console.log(group(arr,6))
完。