Lodash笔记-chunk

9次阅读

共计 675 个字符,预计需要花费 2 分钟才能阅读完成。

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单

1.chunk 方法
// 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]]

正文完
 0