在项目中使用通常会遇到一个数组需要分多行显示,类似于瀑布流的方式,在这种场景下我们需要对一维数组进行转换为二维数组。我们可以使用lodash的chunk方法进行转换。
- 基本用法
_.chunk(array, [size=1])
- 解析
一起来看一下lodash如何实现的chunk方法。- 首先是引入三个函数和定义了两个方法
// 截取数组的起始部分和结束部分之间的数组并返回 var baseSlice = require('./_baseSlice'), // isIterateeCall = require('./_isIterateeCall'), toInteger = require('./toInteger'); // 声明获取最大值和最小值的方法 var nativeCeil = Math.ceil, nativeMax = Math.max;
- 然后就是主要方法
function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { 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)); // 遍历生成数组的每一项 while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; }