Lodash 常用函数
1. 工具定位
Section titled “1. 工具定位”Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。极大地降低了操作数组、对象及函数的底层门槛。
安装依赖:npm i --save lodash
2. 核心业务场景实战代码
Section titled “2. 核心业务场景实战代码”2.1. 函数节流 (Throttle)
Section titled “2.1. 函数节流 (Throttle)”常用于限制高频事件(如 Scroll, Resize, 按钮连击)的执行频率。
// 保证每 1000ms 内只执行一次_.throttle(function(){ console.log("执行逻辑");}, 1000, { leading: true, // 指定调用在节流开始前触发 (首发响应) trailing: true // 指定调用在节流结束后触发 (兜底响应)});2.2. 复杂集合去重与排序 (Collections)
Section titled “2.2. 复杂集合去重与排序 (Collections)”let members = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 1, 'name': 'C' }];
// 依据特定键名极速去重 (保留首个碰到的)_.uniqBy(members, 'id');
// 利用自定义对比函数去重 (适用于深层嵌套比对)_.uniqWith(res.data.results, function (a, b) { return a.member.id === b.member.id;});
// 基础排序_.sortBy(members, 'id');// 高阶排序,显式指定降序 (desc) 或 升序 (asc)_.orderBy(members, 'id', 'desc');2.3. 数据探查与提取
Section titled “2.3. 数据探查与提取”// 从集合中抽取特定列组成新数组_.map(members, 'id');
// 探测集合中是否存在哪怕一个符合断言的元素 (返回布尔值)_.some(users, { 'user': 'barney', 'active': false });
// 获取多个数组的交集_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');2.4. 对象裁切与进阶 (Objects)
Section titled “2.4. 对象裁切与进阶 (Objects)”let target = { "a": 1, "b": 2, "c": 3 };
// 白名单提取:只保留特定的键_.pick(target, ["a", "c"]);
// 黑名单剔除:删除特定的键_.omit(target, ["b"]);
// 高阶实战:对比新旧两个表单对象,提取出被用户修改过的字段键名集合let keys_changed = _.reduce(this.req, (result, value, key) => { // 若新值与旧值一致,原样返回累加器;若不一致,将该 key 塞入累加器数组 return _.isEqual(value, this.instance_data[key]) ? result : result.concat(key);}, []);3. 拓展趋势:Radash
Section titled “3. 拓展趋势:Radash”随着 ES6+ 原生语法的普及,Lodash 显得过于庞大。Radash 是一个更为现代、轻量、完全由 TypeScript 编写的底层工具库替代品,旨在提供更符合直觉的 API 链。