Lodash

JavaScript工具库,提供模块化、高性能的工具函数。让JavaScript编程更简单。

2012发布年份
John-David Dalton作者

核心特性

Lodash 的设计哲学和关键技术特性

📦 模块化设计

按需引入,支持ES模块和CommonJS

⚡ 高性能

经过优化的算法,性能优于原生实现

🛡️ 零依赖

无外部依赖,体积小,兼容性好

🧪 100%测试覆盖

完整的单元测试,稳定可靠

📚 300+函数

覆盖数组、集合、函数、对象、字符串等操作

🔄 链式调用

支持链式调用,代码更简洁

生态系统

Lodash 核心扩展和官方工具

Lodash/fp

函数式编程版本,自动柯里化,数据最后

函数式 柯里化

Lodash/ES

ES模块版本,支持Tree-shaking

ES模块 Tree-shaking

Lodash-ES

官方ES模块包,推荐使用

官方 推荐

Ramda

函数式编程库,与Lodash互补

函数式 替代

快速入门

# 安装Lodash
npm install lodash

# 或使用ES模块版本
npm install lodash-es

# 完整引入(不推荐)
import _ from 'lodash'
_.chunk(['a', 'b', 'c', 'd'], 2)
// => [['a', 'b'], ['c', 'd']]

# 按需引入(推荐)
import chunk from 'lodash/chunk'
import get from 'lodash/get'
import debounce from 'lodash/debounce'

# 使用lodash-es(支持Tree-shaking)
import { chunk, get, debounce } from 'lodash-es'

配置示例

// 常用函数示例

// 数组操作
import { chunk, compact, flatten, uniq, sortBy } from 'lodash-es'

chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
compact([0, 1, false, 2, '', 3]) // [1, 2, 3]
flatten([1, [2, [3, [4]], 5]]) // [1, 2, [3, [4]], 5]
uniq([2, 1, 2]) // [2, 1]
sortBy([{ age: 20 }, { age: 10 }], 'age') // [{ age: 10 }, { age: 20 }]

// 对象操作
import { get, set, merge, pick, omit } from 'lodash-es'

const obj = { a: { b: { c: 1 } } }
get(obj, 'a.b.c') // 1
get(obj, 'a.b.d', 'default') // 'default'
set(obj, 'a.b.d', 2) // { a: { b: { c: 1, d: 2 } } }

// 函数操作
import { debounce, throttle, memoize } from 'lodash-es'

const debouncedFn = debounce(() => {
  console.log('Debounced!')
}, 300)

const throttledFn = throttle(() => {
  console.log('Throttled!')
}, 300)

// 集合操作
import { map, filter, find, reduce, groupBy } from 'lodash-es'

const users = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 25 }
]

groupBy(users, 'age')
// { 25: [{ name: 'John', ... }, { name: 'Bob', ... }], 30: [{ name: 'Jane', ... }] }

学习资源

与其他工具库对比

vs Underscore.js

Lodash性能更好,API更一致,功能更丰富。Underscore更轻量但功能有限。

vs Ramda

Lodash实用为主,Ramda函数式编程为主。Lodash学习曲线更低。