3 回答
TA贡献1995条经验 获得超2个赞
想要几个为一组就把sliceNum改为几~~
const arr = [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]
const len = arr.length
let result = []
const sliceNum = 4
for(let i = 0; i < len / sliceNum; i++){
result.push(arr.slice(i * sliceNum, (i+1) * sliceNum))
}
for(let j = 0; j < (sliceNum - len % sliceNum); j++) {
result[result.length - 1].push({})
}
console.log(result)
TA贡献1852条经验 获得超1个赞
let arr = [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}];
var result = new Array()
for (var i = 0; i < arr.length; i += 4){
var tmp = new Array()
for (var j = 0; j < 4; j++){
if ((i+j) >= arr.length) {
tmp.push({})
continue
}
tmp.push(arr[i+j])
}
result.push({tmp})
}
console.log(result)
添加回答
举报