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]