高阶函数和函数组合通过接受或返回函数、连接函数执行流程,提升代码简洁性与可维护性,如 map、filter 及 compose、pipe 实现数据转换。

函数式编程在JavaScript中越来越受欢迎,核心在于将函数作为一等公民使用。高阶函数和函数组合是其中的关键技巧,能帮助我们写出更简洁、可读性更强、易于测试的代码。
什么是高阶函数
高阶函数是指满足以下任一条件的函数:
- 接受一个或多个函数作为参数
- 返回一个函数
JavaScript中的数组方法如 map、filter、reduce 都是典型的高阶函数。
例如:
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(x => x * 2); // [2, 4, 6, 8] const evens = numbers.filter(x => x % 2 === 0); // [2, 4]
这里 map 和 filter 接收函数作为参数,是标准的高阶函数用法。
立即学习“Java免费学习笔记(深入)”;
函数组合的基本思想
函数组合(Function Composition)指的是将多个函数“连接”起来,前一个函数的输出作为下一个函数的输入。
数学上表示为:(f ∘ g)(x) = f(g(x))
我们可以实现一个通用的 compose 函数:
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
使用示例:
const toUpper = str => str.toUpperCase(); const addExclamation = str => str + '!'; const shout = compose(addExclamation, toUpper);shout('hello'); // "HELLO!"
执行顺序是从右到左:先转大写,再加感叹号。
实用技巧:管道与柯里化配合
有时从左到右的执行顺序更符合直觉,可以实现一个 pipe 函数:
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
结合柯里化(Currying),可以让函数更灵活复用:
const add = x => y => x + y; const multiply = x => y => x * y;const calc = pipe( add(1), multiply(2) );
calc(5); // (5 + 1) * 2 = 12
这种写法让数据处理流程清晰,避免中间变量污染。
实际应用场景
在处理复杂数据转换时,比如格式化用户输入:
const trim = str => str.trim(); const split = delimiter => str => str.split(delimiter); const first = arr => arr[0];const getFirstWord = pipe( trim, split(' '), first );
getFirstWord(' hello world '); // "hello"
每个函数职责单一,组合后形成完整逻辑,便于单元测试和维护。
基本上就这些。高阶函数和组合技巧让代码更具表达力,减少副作用,提升可维护性。不复杂但容易忽略。











