lodash源码分析每日一练 - 数组 - chunk

今日分享:

每一步都是曼妙的风景~

_.chunk(array, [size=1])

使用:
将数组(array)拆分成多个长度(size)的区块,并将这些区块生成一个新的数组。如果最后剩余的内容不够一个区块长度,那不足的那部分为一个区块。
使用示例:

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
 
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

尝试手写:

①返回新数组;②按size截取;③剩余部分自动为一个区块

	let arr = [1,2,4,5,7,8,3,5,6,5]
    function my_chunk (arr,size) {
        const newArr = [];
        for(var i = 0; i < arr.length; i+size){
            newArr.push(arr.splice(i, i+size))
        }
        return newArr
    }
    console.log(my_chunk(arr,4)); // [[1,2,4,5],[7,8,3,5],[6,5]

源码方案:

function chunk(array, size, guard) {
	 var nativeCeil = Math.ceil,
	   nativeMax = Math.max;
	// 非核心方法处理逻辑,guard表示是受保护的方法(注:即这些方法不能使用_.every,_.filter,_.map,_.mapValues,_.reject, 和_.some作为 iteratee 迭代函数参数
	 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;
}

for & while

所有for循环都可以用while实现,for是while的语法糖。
用法区别:一般来说,在循环结构中动态改变循环变量的值时,建议使用 while 结构,而对于静态的循环变量,则可以考虑使用 for 结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值