arr=[1,2,3,4,5,6,7,8,9,10]对于该数组按照步长动态取数据,如何实现? var arr=[1,2,3,4,5,6,7,8,9,10] var eachGroup=[] for(var i=0;i<arr.length/3;i++){
tmp=[]
tmp.push(i); while(i+3<arr.length){
tmp.push(i+3);
}
eachGroup.push(tmp)
} console.log(eachGroup)
1 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
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 ] ]
添加回答
举报
0/150
提交
取消