创建数组
const a = [1, 2, 3];
const b = new Array(5); // 长度 5 的空数组
const c = Array.of(1, 2, 3); // [1, 2, 3]
const d = Array.from('abc'); // ['a', 'b', 'c']
const e = Array.from({length: 5}, (_, i) => i * 2); // [0,2,4,6,8]
const f = [...new Set([1,1,2,3])]; // 去重 → [1,2,3]
基础访问
arr[0] // 第一个
arr[arr.length - 1] // 最后一个
arr.at(-1) // 同上(更现代,Node 16+)
arr.length // 长度
增删改(会改原数组)
arr.push(x) // 末尾加 → 返回新长度
arr.pop() // 末尾弹 → 返回该值
arr.unshift(x) // 开头加
arr.shift() // 开头弹
arr.splice(i, n) // 从 i 删 n 个
arr.splice(i, 0, x) // 在 i 插入 x
arr.splice(i, n, ...new) // 删 n 个再插入 new
arr.reverse() // 原地反转
arr.sort() // 原地排序(默认字符串排)
arr.sort((a, b) => a - b) // 数字排(升)
arr.sort((a, b) => b - a) // 数字排(降)
高阶方法(不改原数组,返回新的)
map:每个元素变换
[1, 2, 3].map(x => x * 2) // [2, 4, 6]
users.map(u => u.name) // 取所有名字
filter:过滤
[1, 2, 3, 4].filter(x => x % 2 === 0) // [2, 4]
users.filter(u => u.age >= 18)
reduce:折叠成单值
[1, 2, 3, 4].reduce((sum, x) => sum + x, 0) // 10
// 分组
users.reduce((acc, u) => {
(acc[u.role] = acc[u.role] || []).push(u);
return acc;
}, {});
// { admin: [...], user: [...] }
find / findIndex
[1, 2, 3].find(x => x > 1) // 2(第一个匹配)
[1, 2, 3].findIndex(x => x > 1) // 1(索引)
users.find(u => u.id === 42)
some / every
[1, 2, 3].some(x => x > 2) // true(有任何匹配)
[1, 2, 3].every(x => x > 0) // true(全部匹配)
includes
[1, 2, 3].includes(2) // true
['a', 'b'].includes('c') // false
forEach(不返回)
[1, 2, 3].forEach(x => console.log(x));
// 想要 break / return 时不能用 forEach,用 for-of
现代方法(不变原数组的复制版本)
Node 20+:
arr.toSorted() // 排序,返回新(不动原)
arr.toReversed() // 反转,返回新
arr.toSpliced(0, 1) // splice,返回新
arr.with(0, 'new') // 改 index 0,返回新
扁平化
[1, [2, 3], [4, [5]]].flat() // [1, 2, 3, 4, [5]]
[1, [2, 3], [4, [5]]].flat(Infinity) // [1, 2, 3, 4, 5]
users.flatMap(u => u.tags) // map + flat 一步
切片 / 拼接
arr.slice(1, 3) // 返回 arr[1..3),不变原
arr.concat(otherArr) // 拼接,返回新
[...a, ...b] // 同上,更现代
转字符串
[1, 2, 3].join('-') // '1-2-3'
[1, 2, 3].toString() // '1,2,3'
for-of vs for-in
for (const x of [10, 20, 30]) { ... } // ✓ 值
for (const [i, x] of arr.entries()) {...} // ✓ 索引 + 值
for (const i in [10, 20, 30]) { ... } // ✗ 索引(也遍历原型)— **少用**
性能小提示
- 简单遍历
for-of比forEach略快(不创建函数调用栈) - 链式
arr.filter(...).map(...).reduce(...)多遍历几次——上百万数据时合一遍 findIndex+splice删某项性能差——大数据用 Map / Set
坑
sort()默认按字符串排:[10, 2, 1].sort()→[1, 10, 2]!数字必须传比较函数Array(5)是长度 5 的空槽(不是[undefined, ...])——map跳过空槽splice改原数组、slice不改——别混- 比较数组:
[1,2] === [1,2]是 false(引用比较)
下一篇:字符串。