JavaScript函数式编程如何实践?

JavaScript函数式编程强调用纯函数、高阶函数、不可变更新、柯里化等方式组织逻辑,提升可预测性、可测试性与可维护性。

JavaScript函数式编程不是要完全抛弃命令式写法,而是用更可预测、更易测试、更少副作用的方式组织逻辑。核心在于把函数当“一等公民”来用:作为参数传入、作为返回值输出、不依赖或修改外部状态。

用纯函数替代带副作用的操作

纯函数指相同输入永远返回相同输出,且不修改外部变量、不发起请求、不读写 DOM。比如把数组去重写成纯函数:

避免这样(依赖外部变量、修改原数组):

let seen = new Set();
const unique = arr => arr.filter(x => {
  if (seen.has(x)) return false;
  seen.add(x);
  return true;
});

改成这样(输入即输出,无外部依赖):

const unique = arr => [...new Set(arr)];
// 或手动实现:
const unique = arr => arr.reduce((acc, x) => acc.includes(x) ? acc : [...acc, x], []);
  • 每次调用都只看输入数组,不关心上次执行过什么
  • 原数组不会被修改,返回新数组
  • 方便单元测试:unique([1,1,2]) === [1,2]

用高阶函数组合行为,而不是层层嵌套

把常用操作抽象为接收函数、返回函数的高阶函数,让逻辑像搭积木一样组合:

const map = fn => arr => arr.map(fn);
const filter = fn => arr => arr.filter(fn);
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);

// 组合使用
const processUsers = pipe(
  filter(user => user.active),
  map(user => ({ id: user.id, name: user.name.toUpperCase() })),
  map(user => ({ ...user, label: `ID${user.id}: ${user.name}` }))
);
  • 每个小函数职责单一,容易复用和测试
  • pipe 让数据流自上而下清晰可见,比嵌套调用更易读
  • 不修改原始数据,每一步都产生新结构

用不可变更新代替直接赋值

避免直接改对象或数组属性,改用展开语法、Object.assign、结构化赋值等方式生成新值:

// ❌
user.name = 'Alice';
items.push(newItem);

// ✅
const newUser = { ...user, name: 'Alice' };
const newItems = [...items, newItem];
const updatedCart = { ...cart, items: newItems };
  • React/Vue 等框架依赖对象引用变化做更新,不可变更新是前提
  • 配合 immer 可以写得更自然,但底层仍是生成新对象
  • 调试时更容易追踪某次状态变更来自哪次操作

用柯里化和偏函数减少重复参数

把多参数函数拆成多个单参数函数,提前固定部分参数,提升复用性:

const add = (a, b) => a + b;
const add5 = b => add(5, b); // 手动柯里化
// 或通用柯里化工具
const curry = fn => (...args) =>
  args.length >= fn.length ? fn(...args) : (...next) => curry(fn)(...args, ...next);

const multiply = (a, b, c) => a * b * c;
const double = curry(multiply)(2);
double(3)(4); // → 24
  • 适合配置型函数,比如 log(level, msg) → logError = log('error')
  • 和函数组合搭配使用,让 pipe 中的步骤更灵活
  • 不必每次传全量参数,语义更清晰