Lodash是一个一致性、模块化、高性能的 JavaScript 实用工具库。Lodash 经过下降 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单数组
// nativeMax = Math.max // nativeCeil = Math.ceil // toInteger转化为整数的方法 // baseSlice切割数组的方法;相似slice function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { //转化size为正整数或者0 size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, //肯定返回数组的长度 向上取整 result = Array(nativeCeil(length / size)); //核心部分 很精简的循环赋值数组指定位置为原数组切割的部分 //在实现slice中也是相似循环赋值方法 while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } chunk([1,2,3,4,5],2)==>[[1,2],[3,4],[5]]