深入浅出lodash之Array的chunk和slice
发布于 6 年前 作者 sunfeng90 2423 次浏览 来自 分享

一、lodash版本:4.16.1

二、函数。 1、chunk 1)含义:将一个数组拆封成多个size大小的数组,然后将多个数组组成一个新的数组。

  1. 例子。

     const _ = require('lodash');
     console.log(_.chunk([1, 2, 3, 4, 5, 6], 4)); // 输出:[ [ 1, 2, 3, 4 ], [ 5, 6 ] ]
     console.log(_.chunk([1, 2, 3, 4, 5, 6], 2)); // 输出:[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]  
     
    

3)源码解读。

(1)首先计算size。如果size小于0,则size 的值为0。否则size取本身的值。 (2)接着计算数组的长度。如果数组为空,长度就为0,否则就为数组的长度。 (3)如果长度不存在或者size为0,那么直接返回空数组。具体源码,如下所示。

 size = Math.max(size, 0)
 const length = array == null ? 0 : array.length
 if (!length || size < 1) {
        return []
 }

(4)生成一个数组,该数组的长度为大于等于length/size的值,并且接近length/size的整数。具体源码,如下所示。

  let index = 0
  let resIndex = 0
  const result = new Array(Math.ceil(length / size))

(5)接着循环,截取数组并插入result中,最后返回result。具体源码,如下所示。

  while (index < length) {
         result[resIndex++] = slice(array, index, (index += size))
   }
  return result

2、slice 1)含义:截取数组。截取包含start位置开始到end位置的新数组。end默认值为数组的长度,start默认值为0。 2)格式: _.slice(array, [start=0], [end = array.length])

  1. 实例:

     const _ = require('lodash');
     console.log(_.slice([1, 2, 3, 4, 5], 3)) // 输出:[ 4, 5 ]
     console.log(_.slice([1, 2, 3, 4, 5], 2)) // 输出:[ 3, 4, 5 ]
    

4)源码解读。

   let length = array == null ? 0 : array.length      //计算length的值。如果数组为空,length为0,否则为数组的长度。
    if (!length) {           //如果length为0,则返回空数组
       return []
    }
    start = start == null ? 0 : start // start如果为空,这start为0,否则就是start本身。
    end = end === undefined ? length : end // end如果不存在,则end为数组的长度,否则就为end值本身。

    if (start < 0) { // 如果start小于0,则判断start的绝对值。如果start的绝对值大于数组的长度,则start设置为0。如果start的绝对值小于数组的长度,则start设置为length                              + start的值。
           start = -start > length ? 0 : (length + start) 
   }
  end = end > length ? length : end // 计算end的值。如果end大于length,那么end取值为length,否则取end。
  if (end < 0) { // 如果end小于0,就计算length+end的值,并赋值给end。此处之所以没有判断-end 是否大于length,是因为end是结束值,而不是start值,没有必要。
       end += length
   }
  length = start > end ? 0 : ((end - start) >>> 0) // 判断start是否大于end,如果大于end,则length取值0。否则计算end - start的值。
  start >>>= 0
  let index = -1
  const result = new Array(length) // 生成一个长度为length的数组。
  while (++index < length) {
             result[index] = array[index + start] // 取出array中特定的元素插入到result中。
   }
  return result
回到顶部