Lodash - 方法
Lodash - 核心概念:链式调用
Section titled “Lodash - 核心概念:链式调用”除了单个函数之外,Lodash 提供了一种强大的方式,可以使用链式调用 (chaining) 优雅地组合多个操作(operations)。这允许你将一个值通过一系列 Lodash 方法传递,而无需使用临时变量(temporary variables)来存放中间结果(intermediate results)。
Lodash 提供了两种主要的链式调用方式:
1. 显式链式调用 (Explicit Chaining)
Section titled “1. 显式链式调用 (Explicit Chaining)”你通过调用 _.chain(value) 来开始一个显式链。这将初始 value 封装在一个 Lodash 包装器对象(wrapper object)中。在此包装器上调用的后续 Lodash 方法将作用于被包装的值并返回一个新的包装器。要从链中获取最终结果,你必须调用 .value() 方法。
语法与示例 (Syntax & Example)
Section titled “语法与示例 (Syntax & Example)”const users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 1, 'active': true }];
const youngestActiveUserName = _.chain(users) .filter({ 'active': true }) // 筛选活跃用户 .sortBy('age') // 按年龄排序(升序) .map('user') // 提取 'user' 属性 .head() // 获取第一个元素(最年轻的) .value(); // 从包装器中提取最终值
console.log(youngestActiveUserName); // => 'pebbles'2. 隐式链式调用 (Implicit Chaining)(通过 lodash/fp 或使用 _())
Section titled “2. 隐式链式调用 (Implicit Chaining)(通过 lodash/fp 或使用 _())”使用主 Lodash 构建版本时,调用 _(value)(注意是单个下划线)通常会为许多方法启动隐式链式调用。那些通常返回新数组或对象的方法(如 map、filter、reject)允许进一步链式调用,而无需调用 .chain()。然而,返回单个值的方法(如 find、sum、head、max)会立即返回该值,从而终止隐式链。
lodash/fp 模块(函数式编程变体 functional programming variant)天然使用隐式链式调用以及数据后置(data-last)、自动柯里化(auto-curried)的函数,这提倡一种不同的组合方式(composition)风格。
隐式链式调用示例(标准 Lodash)
Section titled “隐式链式调用示例(标准 Lodash)”const users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 1, 'active': true }];
// 注意:这里的 .head() 终止了隐式链const youngestActiveUser = _(users) .filter({ 'active': true }) .sortBy('age') .head(); // 直接返回用户对象,而不是包装器
console.log(youngestActiveUser);// => { user: 'pebbles', age: 1, active: true }
// 要在 .head() 后继续链式调用,你需要显式链式调用或处理结果。链式调用的优点 (Benefits of Chaining)
Section titled “链式调用的优点 (Benefits of Chaining)”-
可读性 (Readability): 链式调用通常读起来就像一系列步骤,使复杂的转换(transformations)更容易理解。
-
简洁性 (Conciseness): 减少对中间变量(intermediate variables)的需求。
-
可组合性 (Composability): 鼓励将问题分解为更小、可重用的步骤。
当你需要完全控制并想确保所有步骤都保留在链中直到你显式调用 .value() 时,选择显式链式调用(_.chain())。隐式链式调用对于中间步骤自然返回集合(collections)的序列可以更简洁。
在官方 Lodash 文档中了解更多关于链式调用的信息。