lodash方法之chunk

42 阅读1分钟

自己最近忙手上的项目,发现借助AI太严重了,每次想写一个方法或者看不懂的报错都会问AI,编码能力越来越差,所以决定自己动手写写,然后再看别人是怎么写的,先从lodash的方法开始吧。

第一个方法是lodash的._cunk()方法

试例是这样子的

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

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

首先我自己开始写,用slice方法去截取,根据传入的数值去循环,像这样。

const chunk = (array, num) =>{
    if(array.length > 0 && num) {
        let obj = []
        for(let i = 0 ; i < array.length; i+=num) {
            obj.push(array.slice(i, i + num))
        }
        return obj
    }
}

写的比较简单,利用slice方法根据传入的num与数组的长度来截取。然后我问了一下AI,看它怎么写,他是这样写的

` function chunk2(array, size) { // 处理 size 参数:转为非负整数,无效时默认为 0 size = Math.max(Math.floor(size), 0); const arr = array || []; // 处理 null/undefined 输入 const length = arr.length; if (!length || size < 1) return []; // 边界条件

// 预分配结果数组空间(提升性能) const result = new Array(Math.ceil(length / size)); let resultIndex = 0; let index = 0;

// 循环切割原数组 while (index < length) { // 手动截取子数组(避免依赖 slice) const temp = []; let count = 0; while (count < size && index < length) { temp.push(arr[index]); index++; count++; } result[resultIndex++] = temp; }

return result; } `

Math.max(Math.floor(size), 0); 这写法有点陌生,然后利用了while函数双重循环了两次,我觉得从理解上肯定没有slice好,但是他的解释是如果遇到类数组的情况,slice是需要转换的,而while不需要。