贝利信息

什么是javascript高阶函数_怎样使用map、filter和reduce?

日期:2025-12-25 00:00 / 作者:夜晨
JavaScript高阶函数指接受函数为参数或返回函数的函数,map、filter、reduce是最具代表性的三个:map对每个元素变换生成新数组,filter筛选符合条件元素生成新数组,reduce累积计算返回单值,三者纯函数、可链式调用。

JavaScript 高阶函数是指**接受函数作为参数,或返回函数作为结果的函数**。map、filter、reduce 是最常用、最具代表性的高阶函数,它们让数组操作更简洁、可读性更强,也更容易组合与复用。

map:对每个元素做变换,返回新数组

map 不修改原数组,而是遍历每个元素,把回调函数的返回值组成一个新数组。

例如:

const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2); // [2, 4, 6]
const names = users.map(user => user.name); // 提取所有用户名

filter:筛选符合条件的元素,返回新数组

filter 同样不改变原数组,它只保留回调函数返回 true 的那些元素。

例如:

const scores = [85, 92, 67, 99, 54];
const passing = scores.filter(score => score >= 70); // [85, 92, 99]

reduce:把数组“压缩”成一个值

reduce 从左到右累积处理数组,最终返回单个结果(可以是数字、对象、数组、字符串等)。

例如:

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0); // 10
const groupedByLength = words.reduce((obj, word) => {
  const len = word.length;
  obj[len] = (obj[len] || 0) + 1;
  return obj;
}, {}); // 按长度统计单词数量

组合使用:让逻辑更清晰、更函数式

这三个方法可以链式调用,顺序表达数据流,避免中间变量和 for 循环嵌套。

例如:

const totalActivePrice = products
  .filter(p => p.status === 'active')
  .map(p => p.price)
  .reduce((sum, price) => sum + price, 0);

不复杂但容易忽略:它们都是纯函数(不改原数组),且天然支持箭头函数和简洁写法,是写出清晰、可维护 JavaScript 的基础能力。