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]]