跳到主要内容

高阶函数

高阶函数(Higher-Order Functions)是函数式编程的核心概念之一,它指的是接受函数作为参数或返回函数作为结果的函数。

什么是高阶函数?

一个函数如果满足以下任一条件,就是高阶函数:

  1. 接受一个或多个函数作为参数
  2. 返回一个函数作为结果

常见的高阶函数

1. map

map 函数接受一个函数和一个数组,将该函数应用于数组的每个元素,返回新的数组。

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
// [2, 4, 6, 8, 10]

2. filter

filter 函数接受一个谓词函数和一个数组,返回满足条件的元素组成的新数组。

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(x => x % 2 === 0);
// [2, 4]

3. reduce

reduce 函数接受一个归约函数和一个初始值,将数组归约为单个值。

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, x) => acc + x, 0);
// 15

自定义高阶函数

// 接受函数作为参数
function applyOperation(x, y, operation) {
return operation(x, y);
}

const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

applyOperation(5, 3, add); // 8
applyOperation(5, 3, multiply); // 15

// 返回函数的函数
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}

const triple = multiplyBy(3);
triple(4); // 12

高阶函数的优势

  1. 代码复用:抽象通用模式
  2. 声明式编程:描述"做什么"而非"怎么做"
  3. 组合性:易于组合多个函数
  4. 延迟执行:可以创建延迟计算的函数

实践建议

  • 优先使用内置的高阶函数
  • 提取重复逻辑为高阶函数
  • 保持函数纯粹,避免副作用