function chunk(array, size, guard)
创建一个元素数组,按照“size”的长度分组。
如果 array
不能被平均分割,最后的块将是剩余的元素。
@param {Array} array The array to process.
要处理的数组
@param {number} [size=1] The length of each chunk
每个块的长度,默认 size 等于 1
@param- {Object} [guard] Enables use as an iteratee for methods like
_.map
.
允许用作_.map
等方法的迭代对象。(可选参数)
function chunk(array, size, guard) {
// guard 判断是否用作调用 map 等迭代
// 一般按照使用的话是没有第三个参数的,所以 if 的判断直接来到 size === undefined ?
// 如果不传参数,那么 if 条件满足,size 取默认值1
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
// 如果传递了 size 参数,这时候调用 _.toInteger 将 size 转化成整数,因为无可避免用户会输入其他类型的参数
// nativeMax = Math.max 转化后的 size 和 0 相比较,取两者之间最大值
size = nativeMax(toInteger(size), 0);
}
// 获取数组的长度 length
var length = array == null ? 0 : array.length;
// 判断 length 和 size,如果数组不存在或者 size 参数错误,则返回空数组
if (!length || size < 1) {
return [];
}
// 初始化变量,index[下标]、resIndex[result 结果的下标]、result[结果数组]
var index = 0,
resIndex = 0,
// Array(nativeCeil(length / size))
// nativeCeil = Math.ceil() 向上取整
// 这一步的作用是生成一个有确认长度结果数组
result = Array(nativeCeil(length / size));
// 循环
while (index < length) {
// 对 result 的每一项重新赋值
// 调用 _.baseSlice 进行数组裁剪
// 首先传参中,第三个参数 index += size 不仅给出了 baseSlice 需要的 end[结尾下标] 参数,也对 index 做出了修改
result[resIndex++] = baseSlice(array, index, (index += size));
// 下次 index < length 时,index 的值便成了 += size 后的结果
}
return result;
}
总结
- 对 size 参数作处理,如果 size 不存在则默认为 1,若 size 存在,则取整且和 0 比较取最大值;
- 获取数组长度,若数组不存在,则长度为 0;
- 判断长度是否存在,或size是否小于1(这一步第一个条件是判断数组是否存在,第二个条件是 size 参数是否合法);
- 创建变量,原数组下标、新数组下标、用长度/size生成的新数组
- 遍历,新数组每项赋值截取后的内容
网友评论