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

一. 写在前面:数组


本系列使用 lodash 4.17.4版本浏览器

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

二. 函数使用示例函数


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]
复制代码

三. 模块代码:post


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
复制代码

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


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

  2. function chunk(array, size) {}.net

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

    (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 写法

相关文章
相关标签/搜索