var arr=[1,2,3,4,8,9,2,3,4] function chunk(array, size) { //獲取數組的長度,如果你傳入的不是數組,那么獲取到的就是undefined const length = array.length //判斷不是數組,或者size沒有設置,size小於1,就返回空數組 if (!length || !size || size < 1) { return [] } //核心部分 let index = 0 //用來表示切割元素的范圍start let resIndex = 0 //用來遞增表示輸出數組的下標 //根據length和size算出輸出數組的長度,並且創建它。 let result = new Array(Math.ceil(length / size)) //進行循環 while (index < length) { //循環過程中設置result[0]和result[1]的值。該值根據array.slice切割得到。 result[resIndex++] = array.slice(index, (index += size)) } //輸出新數組 return result }