Lodash源码阅读-drop

Lodash 源码阅读-drop

概述

drop 函数是 Lodash 库中的一个数组操作工具,作用是从数组开头删除指定数量的元素并返回剩余部分。简单来说,它就是切掉数组的前几个元素,并返回一个新数组,原数组不会被修改。

前置学习

依赖函数

  • baseSlice :Lodash 内部的数组切片函数,drop 的核心实现依赖于它
  • toInteger :将输入值转换为整数,用来处理参数 n

技术知识

  • 数组切片:从数组中提取部分元素的操作
  • 参数默认值:当参数未提供时使用的值
  • 类型转换:将不同类型的值转换为整数
  • 空值检查 :检查和处理 nullundefined
  • Guard 参数:Lodash 内部用于高阶函数的特殊参数

源码实现

javascript 复制代码
/**
 * Creates a slice of `array` with `n` elements dropped from the beginning.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=1] The number of elements to drop.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.drop([1, 2, 3]);
 * // => [2, 3]
 *
 * _.drop([1, 2, 3], 2);
 * // => [3]
 *
 * _.drop([1, 2, 3], 5);
 * // => []
 *
 * _.drop([1, 2, 3], 0);
 * // => [1, 2, 3]
 */
function drop(array, n, guard) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return [];
  }
  n = guard || n === undefined ? 1 : toInteger(n);
  return baseSlice(array, n < 0 ? 0 : n, length);
}

实现思路

drop 函数的实现非常直接:

  1. 检查输入数组是否为 null/undefined 或空数组,如果是则返回空数组
  2. 处理参数 n(要删除的元素数量):
    • 如果 n 未提供或有 guard 参数,使用默认值 1
    • 否则,将 n 转换为整数
  3. 调用 baseSlice 从索引 n 切割到数组末尾
    • 如果 n 为负数,则从索引 0 开始(相当于不删除任何元素)
  4. 返回切片结果

源码解析

空值和边界检查

javascript 复制代码
var length = array == null ? 0 : array.length;
if (!length) {
  return [];
}

这段代码处理两种情况:

  • arraynullundefined 时,将 length 设为 0
  • 当数组长度为 0 时,直接返回空数组

使用 == 而不是 === 可以同时检查 nullundefined,这是一种常见的简写技巧。

参数处理

javascript 复制代码
n = guard || n === undefined ? 1 : toInteger(n);

这行代码决定删除多少个元素:

  • 如果有 guard 参数(在 _.map 等高阶函数中使用时)或 n 未定义,使用默认值 1
  • 否则,调用 toIntegern 转换为整数

这种处理确保了 n 总是一个合理的整数,无论传入的是什么类型的值。

切片操作

javascript 复制代码
return baseSlice(array, n < 0 ? 0 : n, length);

最后,调用 baseSlice 函数执行实际的切片操作:

  • 从索引 n 开始(如果 n 小于 0,则从 0 开始)
  • 到数组结尾(length
  • 返回这个新的切片数组

baseSlice 函数比原生的 Array.prototype.slice 更高效,尤其是在处理边界情况时。

总结

drop 函数是 Lodash 中一个简单但实用的数组操作工具,它有以下几个特点:

  1. 简单明了:功能单一,易于理解和使用
  2. 不变性:不修改原数组,返回新数组,符合函数式编程原则
  3. 健壮性 :正确处理各种边界情况,如空数组、null 值和负数参数
  4. 灵活性:可以与其他 Lodash 函数组合使用,构建更复杂的数据处理流程

虽然现代 JavaScript 可以通过 Array.prototype.slice(n) 实现类似功能,但 _.drop 提供了更一致的行为和更好的空值处理,特别是在处理可能为 nullundefined 的数组时。

相关推荐
风中飘爻14 分钟前
JavaScript:BOM编程
开发语言·javascript·ecmascript
恋猫de小郭16 分钟前
Android Studio Cloud 正式上线,不只是 Android,随时随地改 bug
android·前端·flutter
清岚_lxn5 小时前
原生SSE实现AI智能问答+Vue3前端打字机流效果
前端·javascript·人工智能·vue·ai问答
ZoeLandia5 小时前
Element UI 设置 el-table-column 宽度 width 为百分比无效
前端·ui·element-ui
橘子味的冰淇淋~6 小时前
解决 vite.config.ts 引入scss 预处理报错
前端·vue·scss
萌萌哒草头将军7 小时前
💎这么做,cursor 生成的代码更懂你!💎
javascript·visual studio code·cursor
小小小小宇7 小时前
V8 引擎垃圾回收机制详解
前端
lauo8 小时前
智体知识库:ai-docs对分布式智体编程语言Poplang和javascript的语法的比较(知识库问答)
开发语言·前端·javascript·分布式·机器人·开源
拉不动的猪8 小时前
设计模式之------单例模式
前端·javascript·面试
一袋米扛几楼988 小时前
【React框架】什么是 Vite?如何使用vite自动生成react的目录?
前端·react.js·前端框架