数组是 JS 使用率最高的结构。本文按增删改、遍历、变换、排序分类讲透常用方法,结尾附成绩处理小案例。
一、创建与访问
const arr = [1, 2, 3];
const arr2 = new Array(3); // [空×3](慎用,易混)
const arr3 = Array.from('abc'); // ['a','b','c']
const arr4 = Array.of(1, 2); // [1, 2]
arr[0] // 访问
arr.length // 长度
arr.at(-1) // 取最后一个(ES2022,免 arr[arr.length-1])
二、增删改
arr.push(4, 5) // 尾增,返回新长度
arr.pop() // 尾删,返回被删值
arr.unshift(0) // 头增(大量元素慢)
arr.shift() // 头删
arr.splice(1, 1) // 从索引1删1个(万能增删改)
arr.splice(1, 0, 'x') // 在索引1插入(不删)
arr.slice(0, 2) // 截取子数组(不改原数组)
arr.concat([4, 5]) // 合并(返回新数组)
splice 改原数组、slice 不改 —— 名字像,作用反。
三、高阶方法(重点)
arr.map(x => x * 2) // 映射变换,返回新数组
arr.filter(x => x > 1) // 过滤
arr.reduce((sum, x) => sum + x, 0) // 累加/归并(初始值 0)
arr.find(x => x.id === 2) // 找第一个匹配(返回元素)
arr.findIndex(x => x > 2) // 找索引
arr.some(x => x > 0) // 任一满足?(布尔)
arr.every(x => x > 0) // 全部满足?
arr.includes(2) // 包含?
arr.flatMap(x => x.split(',')) // map + flatten
map/filter/reduce 三件套几乎承包所有数据变换 —— 背下来。
四、排序(陷阱)
[10, 9, 100].sort() // [10, 100, 9] ❌ 默认按字符串排!
[10, 9, 100].sort((a, b) => a - b) // [9, 10, 100] ✅ 数值升序
[10, 9, 100].sort((a, b) => b - a) // 降序
// 对象数组排序
users.sort((a, b) => b.score - a.score)
// sort 会修改原数组!要拷贝再排:
[...arr].sort(cmp) 或 arr.toSorted(cmp) // ES2023 不改原数组
五、注意
- sort 默认字符串比较("10" < "9")—— 数字必须传比较函数;
- slice/concat/map/filter 都是浅拷贝(嵌套对象仍共享引用);
- splice 会改变原数组,map/filter 不会;
- 判空数组用 arr.length === 0 或 arr.length。
六、小案例:学生成绩处理
const students = [
{ name: 'Tom', score: 92 },
{ name: 'Jerry', score: 58 },
{ name: 'Spike', score: 76 },
{ name: 'Tyke', score: 88 },
];
// 1. 过滤及格、按分数降序、取前 2 名
const top2 = students
.filter(s => s.score >= 60)
.sort((a, b) => b.score - a.score)
.slice(0, 2);
console.log(top2); // Tom, Tyke
// 2. 平均分(reduce)
const avg = students.reduce((sum, s) => sum + s.score, 0) / students.length;
// 3. 加字段(map 返回新数组)
const withLevel = students.map(s => ({
...s,
level: s.score >= 90 ? 'A' : s.score >= 60 ? 'B' : 'C'
}));
// 4. 分组(reduce 实现 groupBy)
const byLevel = students.reduce((acc, s) => {
const k = s.score >= 90 ? 'A' : s.score >= 60 ? 'B' : 'C';
(acc[k] ??= []).push(s);
return acc;
}, {});
console.log(byLevel); // { A: [Tom], B: [Spike, Tyke], C: [Jerry] }
filter→sort→slice 三连、reduce 算平均、map 加字段、reduce 分组 —— 数组方法的实战套路全在这一例。
七、总结
增删用 push/splice、截取用 slice;map/filter/reduce 三件套;sort 必须传比较函数;分组用 reduce;浅拷贝记住 spread。