蛊毒传说
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]var eachGroup = []var step = 3for (var i = 0; i < arr.length; i++) { var item = arr[i] if (i % step === 0) {
eachGroup.push([item])
} else {
eachGroup[eachGroup.length - 1].push(item)
}
}console.log(eachGroup) // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]或者var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]const { eachGroup } = arr.reduce( ({ eachGroup, step }, item, index) => (
index % step === 0
? eachGroup.push([item])
: eachGroup[eachGroup.length - 1].push(item),
{ eachGroup, step }
),
{ eachGroup: [], step: 3 },
)console.log(eachGroup) // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]