lodash是一個工具庫,跟underscore差很少數組
chunk函數的做用: 把一維數組,按照固定的長度分段成二維數組函數
如:工具
1 function chunk(array, size) { 2 size = Math.max(size, 0); 3 const length = array == null ? 0 : array.length; 4 if (!length || size < 1) { 5 return []; 6 } 7 let index = 0; 8 let resIndex = 0; 9 const result = new Array(Math.ceil(length / size)); 10 11 while (index < length) { 12 result[resIndex++] = array.slice(index, (index += size)); 13 } 14 return result; 15 }
第2行: size=Math.max( size, 0 ); 獲取0和size之間的較大值, 縱觀整個函數, 通俗點講就是,若是size是負數,把size變爲0,其實整個函數 有個小bug, 那就是沒有對size是否傳遞參數作判斷,spa
若是這樣用 chunk( [ 10, 20, 30 ] ) 這樣會報錯,由於size沒有傳,默認爲undefined, 在第9行 length / size的時候就會報錯, 因此我認爲更加嚴謹的作法是在第二行代碼之間,再加一句判斷:code
size = ( typeof size === 'undefined' ) ? 0 : size;
for( ; index < length; ) {result[resIndex] = array.slice( index, index + size );resIndex++;index = index + size;}
1 function drop(array, n = 1) { 2 const length = array == null ? 0 : array.length; 3 return length 4 ? array.slice( n < 0 ? 0 : n, length) 5 : []; 6 } 7 8 console.log( drop( [ 10, 20, 30 ] ) ); //[ 20, 30 ] 9 console.log( drop( [ 10, 20, 30 ], 3 ) ); //[] 10 console.log( drop( [ 10, 20, 30 ], 2 ) ); //[30]