按照步长取数据?

依依雨柔
  • 233

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.3k
1 个回答
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var eachGroup = []
var step = 3
for (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 ] ]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏