array/chunk.jsjavascript
/**
* 将数组按指定大小切分为多个子数组,不修改原数组。
* @function chunk
* @memberof module:array
* @param {Array} array 要切分的数组
* @param {number} [size=1] 每个子数组的最大长度
* @returns {Array[]} 切分后的二维数组
* @throws {TypeError|RangeError} 参数类型或 size 不合法时抛出
*/
function chunk(array, size = 1) {
if (!Array.isArray(array)) throw new TypeError('array must be an array')
if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer')
const result = []
for (let index = 0; index < array.length; index += size) result.push(array.slice(index, index + size))
return result
}
export default chunk