方法说明
将数组(array)拆分成多个 size 长度的区块,并将这些区块组成一个新数组(也就是生成一个二维数组)。 如果array 无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。
源码
function chunk(array, size = 1) {
size = Math.max(toInteger(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
}
参数处理
size = Math.max(toInteger(size), 0)
toInteger 将size转换成整数,然后和0比较取最大值,保证size为大于等于0的整数。
const length = array == null ? 0 : array.length
if (!length || size < 1) {
return []
}
当length不存在或者length为0,或size为0时,直接返回一个空数组。
分隔逻辑
const result = new Array(Math.ceil(length / size))
Math.ceil 执行的是向上取整计算,它返回的是大于或等于函数参数,并且与之最接近的整数。这样便计算出需要分块的个数。
let index = 0
let resIndex = 0
while (index < length) {
result[resIndex++] = slice(array, index, (index += size))
}
计算出来需要分割的数量以后,接下来就是分割了。将每次分割的结果放在 result 中。
resIndex 是放置块的位置,index 是分割的开始位置。
当 index 与块的数量 length 相等时,表示已经切割完毕,停止切割,最后将结果返回。
其他
Math.ceil(1) //-> 1
Math.ceil(1.1) //-> 2