chunk函数实现原理

1,286 阅读1分钟

今天在实现小程序项目中遇到了一个轮播的需求,一组轮播里面放三个展示数据,所以就想到了 lodash的——chunk函数,结果看了一下源码觉得甚是复杂,只会切图的我看不懂啊,所以大体根据我的理解自己改变了一个新的chunk函数,可以把数组分割成你想要的样子

function chunk(array, size) {
  //获取数组的长度,如果你传入的不是数组,那么获取到的就是undefined
  const length = array.length
  //判断不是数组,或者size没有设置,size小于1,就返回空数组
  if (!length || !size || size < 1) {
    return []
  }

  //核心部分
  let index = 0 //用来表示切割元素的范围start
  let resIndex = 0 //用来递增表示输出数组的下标

  //根据length和size算出输出数组的长度,并且创建它。
  let result = new Array(Math.ceil(length / size))
  //进行循环
  while (index < length) {
    //循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
    result[resIndex++] = array.slice(index, (index += size))
  }
  //输出新数组
  return result
}

chunk(['a', 'b', 'c', 'd'], 1) //[['a'], ['b'], ['c'], ['d']]
chunk(['a', 'b', 'c', 'd'], 2) //[['a', 'b'], ['c', 'd']]
chunk(['a', 'b', 'c', 'd'], 3) //[['a', 'b', 'c'], ['d']]
chunk(['a', 'b', 'c', 'd'], 4) //[['a', 'b', 'c', 'd']]