掌握数组的操作和现代处理方法
// 字面量创建
const arr1 = [1, 2, 3, 4, 5];
// 使用 Array 构造函数
const arr2 = new Array(1, 2, 3);
// 创建指定长度的数组
const arr3 = new Array(5); // [empty × 5]
// 使用 Array.from
const arr4 = Array.from({ length: 5 }, (_, index) => index + 1); // [1, 2, 3, 4, 5]
// 使用 Array.of
const arr5 = Array.of(1, 2, 3); // [1, 2, 3]| 方法 | 描述 | 示例 |
|---|---|---|
| push() | 在末尾添加元素 | arr.push(6) |
| pop() | 移除末尾元素 | arr.pop() |
| shift() | 移除开头元素 | arr.shift() |
| unshift() | 在开头添加元素 | arr.unshift(0) |
| splice() | 添加/删除元素 | arr.splice(1, 2, 'a', 'b') |
| slice() | 返回子数组 | arr.slice(1, 3) |
| concat() | 合并数组 | arr.concat([4, 5]) |
| join() | 将数组转为字符串 | arr.join(', ') |
// map() - 对每个元素执行操作并返回新数组
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const names = users.map(user => user.name); // ['John', 'Jane']// filter() - 过滤出符合条件的元素
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const adults = users.filter(user => user.age >= 18); // 所有用户// reduce() - 将数组归约为单个值
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0); // 15
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const totalAge = users.reduce((total, user) => total + user.age, 0); // 55// find() - 找到第一个符合条件的元素
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
];
const user = users.find(user => user.id === 1); // { id: 1, name: 'John' }
// some() - 检查是否有元素符合条件
const hasAdult = users.some(user => user.age >= 18); // true
// every() - 检查是否所有元素都符合条件
const allAdults = users.every(user => user.age >= 18); // true
// findIndex() - 找到第一个符合条件的元素的索引
const index = users.findIndex(user => user.id === 2); // 1// 传统方式(创建中间数组)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = numbers
.map(num => num * 2) // 创建第一个中间数组
.filter(num => num > 10) // 创建第二个中间数组
.slice(0, 3); // 创建第三个中间数组
// ES2026 方式(无中间数组)
const result2 = numbers
.map(num => num * 2)
.filter(num => num > 10)
.take(3); // 直接取前 3 个,无中间数组take(n) - 取前 n 个元素drop(n) - 跳过前 n 个元素takeWhile(predicate) - 取元素直到条件不满足dropWhile(predicate) - 跳过元素直到条件不满足flatMap(callback) - 映射后扁平化// 变更方法
const arr = [3, 1, 2];
arr.sort(); // 原数组被修改为 [1, 2, 3]
// 非变更方法
const arr2 = [3, 1, 2];
const sortedArr = arr2.toSorted(); // 原数组不变,返回新数组 [1, 2, 3]// 基本解构
const [a, b, c] = [1, 2, 3]; // a=1, b=2, c=3
// 跳过元素
const [first, , third] = [1, 2, 3]; // first=1, third=3
// 剩余元素
const [first2, ...rest] = [1, 2, 3, 4]; // first2=1, rest=[2, 3, 4]
// 默认值
const [x, y = 10] = [5]; // x=5, y=10// 复制数组
const arr = [1, 2, 3];
const copy = [...arr]; // [1, 2, 3]
// 合并数组
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
// 传递参数
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
sum(...numbers); // 6