JavaScript入门⑤|数组方法全攻略,map/filter/reduce三剑客


author: 专注前端开发,分享JavaScript干货

title: JavaScript入门⑤|数组方法全攻略,map/filter/reduce三剑客
update: 2026-04-28
tags: JavaScript,数组,map,filter,reduce,forEach,find,前端入门

作者:专注前端开发,分享JavaScript干货

更新时间:2026年4月

适合人群:掌握JS基础,想高效处理数据的同学


前言:数组是JS的灵魂

JavaScript中,数组无处不在:列表数据、表格行、用户信息......处理这些数据,全靠数组方法。

ES6+的数组方法让代码从50行变成3行。


一、创建数组

javascript 复制代码
// 基本创建
let arr1 = [1, 2, 3, 4, 5];
let arr2 = new Array(1, 2, 3); // 不推荐

// Array.of(创建单元素数组更安全)
let arr3 = Array.of(5);        // [5],不是5个空位
let arr4 = Array.of(1, 2, 3);   // [1, 2, 3]

// Array.from(从类数组/可迭代对象创建数组)
let strArr = Array.from("hello"); // ["h","e","l","l","o"]
let doubleArr = Array.from([1, 2, 3], x => x * 2); // [2, 4, 6]

二、遍历类方法

2.1 forEach(遍历,不返回值)

javascript 复制代码
const users = [
    { name: "张三", age: 25 },
    { name: "李四", age: 30 },
    { name: "王五", age: 22 }
];

users.forEach((user, index) => {
    console.log(`${index + 1}. ${user.name},${user.age}岁`);
});

// 输出:
// 1. 张三,25岁
// 2. 李四,30岁
// 3. 王五,22岁

2.2 map(返回新数组,每个元素变换)

javascript 复制代码
const prices = [100, 200, 300];

// 打8折
const discounted = prices.map(price => price * 0.8);
console.log(discounted); // [80, 160, 240]

// 对象转换
const users = [
    { firstName: "张", lastName: "三" },
    { firstName: "李", lastName: "四" }
];
const fullNames = users.map(u => `${u.firstName}${u.lastName}`);
console.log(fullNames); // ["张三", "李四"]

2.3 filter(返回满足条件的元素)

javascript 复制代码
const products = [
    { name: "手机", price: 3000, inStock: true },
    { name: "电脑", price: 8000, inStock: false },
    { name: "耳机", price: 500, inStock: true },
    { name: "平板", price: 2000, inStock: true }
];

// 筛选有货商品
const available = products.filter(p => p.inStock);

// 筛选价格在1000-5000之间的
const midRange = products.filter(p => p.price >= 1000 && p.price <= 5000);

console.log("有货商品:", available.map(p => p.name));
console.log("中端产品:", midRange.map(p => p.name));

三、查询类方法

3.1 find / findIndex / findLast

javascript 复制代码
const users = [
    { id: 1, name: "张三" },
    { id: 2, name: "李四" },
    { id: 3, name: "王五" }
];

// 找第一个满足条件的
const user = users.find(u => u.id === 2);
console.log(user.name); // "李四"

// 找索引
const index = users.findIndex(u => u.name === "王五");
console.log(index); // 2

// 找最后一个(ES2023+)
const lastUser = users.findLast(u => u.id > 0);
console.log(lastUser.name); // "王五"

3.2 includes / indexOf / lastIndexOf

javascript 复制代码
const arr = [1, 2, 3, 2, 5];

console.log(arr.includes(2));      // true
console.log(arr.indexOf(2));       // 1(第一个2的索引)
console.log(arr.lastIndexOf(2));   // 3(最后一个2的索引)

3.3 some / every

javascript 复制代码
const products = [
    { name: "手机", price: 3000, inStock: true },
    { name: "电脑", price: 8000, inStock: false }
];

// some:至少有一个满足条件
const hasOutOfStock = products.some(p => !p.inStock);
console.log(hasOutOfStock); // true

// every:所有都满足条件
const allInStock = products.every(p => p.inStock);
console.log(allInStock); // false

四、聚合类方法

4.1 reduce(最强大,也是最需要掌握的)

javascript 复制代码
// 语法:arr.reduce((累计值, 当前元素) => 新累计值, 初始值)

const nums = [1, 2, 3, 4, 5];

// 求和
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

// 求最大值
const max = nums.reduce((acc, n) => n > acc ? n : acc, nums[0]);
console.log(max); // 5(更简单:Math.max(...nums))

// 数组去重
const duplicates = [1, 2, 2, 3, 3, 3, 4];
const unique = duplicates.reduce((acc, n) => {
    if (!acc.includes(n)) {
        acc.push(n);
    }
    return acc;
}, []);
console.log(unique); // [1, 2, 3, 4]

// 对象数组统计
const orders = [
    { category: "电子产品", amount: 3000 },
    { category: "图书", amount: 100 },
    { category: "电子产品", amount: 2000 },
    { category: "图书", amount: 80 }
];
const summary = orders.reduce((acc, order) => {
    if (!acc[order.category]) {
        acc[order.category] = 0;
    }
    acc[order.category] += order.amount;
    return acc;
}, {});
console.log(summary);
// { "电子产品": 5000, "图书": 180 }

4.2 flat / flatMap(数组扁平化)

javascript 复制代码
const nested = [1, [2, 3], [4, [5, 6]]];

// flat:按指定深度展开数组
console.log(nested.flat());        // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2));       // [1, 2, 3, 4, 5, 6]
console.log(nested.flat(Infinity));// 完全展开

// flatMap:先map再flat(常用场景:处理后展开)
const sentences = ["Hello world", "How are you"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["Hello", "world", "How", "are", "you"]

五、排序与反转

javascript 复制代码
const arr = [3, 1, 4, 1, 5, 9, 2, 6];

// sort(默认按字符串Unicode排序)
console.log(arr.sort()); // [1, 1, 2, 3, 4, 5, 6, 9]

// 按数字大小排序(必须传比较函数)
arr.sort((a, b) => a - b); // 升序
console.log(arr); // [1, 1, 2, 3, 4, 5, 6, 9]

arr.sort((a, b) => b - a); // 降序
console.log(arr); // [9, 6, 5, 4, 3, 2, 1, 1]

// reverse
console.log(arr.reverse()); // [1, 1, 2, 3, 4, 5, 6, 9]

六、知识卡

方法 返回值 说明
forEach undefined 遍历,无返回值
map 新数组 每个元素变换
filter 新数组 满足条件才保留
find 元素/null 找第一个匹配
findIndex 索引/-1 找第一个匹配索引
some 布尔 至少一个满足
every 布尔 全部满足
reduce 任意值 聚合/汇总
flat 新数组 扁平化
flatMap 新数组 map+flat

七、实战:销售数据报表

javascript 复制代码
const sales = [
    { month: "1月", region: "华东", product: "手机", amount: 15000 },
    { month: "1月", region: "华东", product: "电脑", amount: 25000 },
    { month: "1月", region: "华南", product: "手机", amount: 12000 },
    { month: "2月", region: "华东", product: "手机", amount: 18000 },
    { month: "2月", region: "华南", product: "电脑", amount: 20000 },
    { month: "2月", region: "华北", product: "手机", amount: 9000 },
];

// 1. 计算总销售额
const totalSales = sales.reduce((sum, s) => sum + s.amount, 0);
console.log(`总销售额:¥${totalSales.toLocaleString()}`);

// 2. 按区域分组统计
const byRegion = sales.reduce((acc, s) => {
    if (!acc[s.region]) acc[s.region] = 0;
    acc[s.region] += s.amount;
    return acc;
}, {});
console.log("各区域销售额:", byRegion);

// 3. 找出销售额Top3的月份
const byMonth = sales.reduce((acc, s) => {
    if (!acc[s.month]) acc[s.month] = 0;
    acc[s.month] += s.amount;
    return acc;
}, {});
const topMonths = Object.entries(byMonth)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 3);
console.log("Top3月份:", topMonths.map(([m, a]) => `${m} ¥${a.toLocaleString()}`));

八、课后作业

  1. reduce 统计一个数组中每个元素出现的次数
  2. filter + map 组合:筛选出价格>100的商品,打印名称和折后价(8折)
  3. 实现一个函数,传入嵌套数组 [1, [2, [3, 4]]],返回扁平化结果

有问题欢迎评论区留言,大家一起讨论!


标签:JavaScript | 数组 | map | filter | reduce | forEach | find | 数组方法

相关推荐
KANGBboy7 小时前
java知识二(程序流程控制)
java·开发语言
threelab7 小时前
Three.js 抽象艺术着色器效果 | 三维可视化 / AI 提示词
前端·javascript·人工智能·3d·着色器
Evand J7 小时前
【MATLAB代码介绍】到达时间(TOA)定位,三维空间,带EKF的轨迹滤波与误差分析
开发语言·matlab
tongluowan0077 小时前
数据结构 Bitmap(位图)完整详解
开发语言·数据结构·bitmap
008爬虫实战录7 小时前
【码上爬】 题十八:模拟大厂加密算法, 堆栈分析找加密点,扣自执行函数,jsdom补环境
开发语言·javascript·ecmascript
skywalk81637 小时前
言知中文编程语言计划书 by WorkBuddy
开发语言·编程
NiceCloud喜云7 小时前
AutoClaw 接入自定义 Anthropic 端点:让 Kanban 工作流跑在自己的模型路由上
java·开发语言·c++·人工智能·python·eclipse·batch
skywalk81637 小时前
脚本 isMobile.js(移动设备检测库)的核心实现
开发语言·javascript·ecmascript
i_am_a_div_日积月累_7 小时前
3.contextBridge桥梁
前端·javascript·vue.js·electron