每日源码分析 - lodash(chunk.js)

一. 写在前面:


本系列使用 lodash 4.17.4版本

这个函数的作用是用来切割数组的,通过传入数组 Array 和块数量 size 来进行数组分割,返回新的数组块.

二. 函数使用示例



function chunk(array, size) {
  size = Math.max(size, 0)
  const length = array == null ? 0 : array.length
  if (!length || size < 1) {
    return []
  }
  let index = 0
  let resIndex = 0
  const result = new Array(Math.ceil(length / size))
  while (index < length) {
    result[resIndex++] = array.slice(index, (index += size))
  }
  return result
}
var ret = chunk(['a', 'b', 'c', 'd'], 2)
console.log(ret)
复制代码

输出结果为:

[ [ 'a', 'b' ], [ 'c', 'd' ] ]
[Finished in 1.2s]
复制代码

三. 模块代码:


import slice from './slice.js'

function chunk(array, size) {
  size = Math.max(size, 0)
  const length = array == null ? 0 : array.length
  if (!length || size < 1) {
    return []
  }
  let index = 0
  let resIndex = 0
  const result = new Array(Math.ceil(length / size))

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

export default chunk
复制代码

四. 对代码的具体解释(以下顺序是按照代码顺序进行解释的)


  1. import slice from './slice.js' 通过 ECMAscript6新特性,引用 slice 模块。

  2. function chunk(array, size) {}

    (1)chunk 函数主体, 参数 array 表示原始数组,为局部变量;

    (2)size 表示拆分后的每个新数组长度,为局部变量。

  3. size = Math.max(size, 0)

    (1)寻找 0~size 之间的最大值,并赋值给size。

    (2)目的是检查传入的 size 值是否大于等于 0,如果 size 小于0,size 取0.

  4. const length = array == null ? 0 : array.length

    (1)声明一个变量length,const 声明的变量需要同时初始化,而且只能赋值一次, 一旦初始化后,该变量的值就不能改变;

    (2) 如果 array is null, then length = 0,否则 length = array.length,这里的条件语句用了简写模式,需要转一下弯,不然容易搞错。

  5. 如果 length 等于0,或者 size 小于 1 时,返回空数组。

if (!length || size < 1) {
    return []
  }
复制代码
  1. 声明块级变量 index、 resIndex
  let index = 0
  let resIndex = 0
复制代码
  1. const result = new Array(Math.ceil(length / size))

    (1)创建一个新的数组 result ,调用Math方法计算length / size 的值,并向上取整。

    (2)给 result 数组分配一个定长的内存空间。

  2. 当 index 小于 length 时,原数组取 index 到 index+size 位元素,存到result数组里。

  while (index < length) {
    result[resIndex++] = slice(array, index, (index += size))
  }
复制代码
  1. return result 返回新的result数组

  2. export default chunk 默认导出函数 chunk

五. 写在最后:


本文章来源于午安煎饼计划Web组 - 初见

由于本人水平有限,很多地方理解不到位,还请各位大佬指正。

相关链接:

每日源码分析-Lodash(castArray.js)

每日源码分析 - lodash ( after.js )

HTML 语义化

关于浏览器内核及其 CSS 写法

你可能感兴趣的:(每日源码分析 - lodash(chunk.js))