在 TypeScript 中遍历数组有多种方式,以下是 7 种常用方法,涵盖不同场景需求:
1. for 循环(最基础)
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(`索引 ${i}: 值 ${arr[i]}`);
}
适用场景:需要索引时,或需控制遍历顺序/步长。
2. for...of(推荐遍历值)
for (const item of arr) {
console.log(item); // 直接获取值
}
优势:简洁,无索引干扰,支持 break/continue。
3. forEach(函数式风格)
arr.forEach((item, index) => {
console.log(`索引 ${index}: 值 ${item}`);
});
特点:
- 无法用
break中断,需抛异常或改用some/every。 - 无返回值(区别于
map)。
4. map(返回新数组)
const doubled = arr.map(item => item * 2);
console.log(doubled); // [2, 4, 6]
用途:需对数组每个元素转换时。
5. filter(条件筛选)
const evens = arr.filter(item => item % 2 === 0);
console.log(evens); // [2]
6. reduce(累积计算)
const sum = arr.reduce((total, item) => total + item, 0);
console.log(sum); // 6
7. for...in(不推荐用于数组)
// ❌ 避免!会遍历原型链且顺序不保证
for (const index in arr) {
console.log(arr[index]);
}
正确用途:遍历对象属性,而非数组。
类型安全的遍历(TS 特性)
interface User {
id: number;
name: string;
}
const users: User[] = [{ id: 1, name: "Alice" }];
// TS 会自动推断 `user` 为 User 类型
users.forEach(user => {
console.log(user.name.toUpperCase()); // 无类型错误
});
如何选择?
| 方法 | 是否需要索引 | 可中断 | 返回值 | 典型用途 |
|---|---|---|---|---|
for |
✅ | ✅ | 无 | 通用遍历 |
for...of |
❌ | ✅ | 无 | 简单值遍历 |
forEach |
✅ | ❌ | 无 | 执行副作用 |
map |
✅ | ❌ | 新数组 | 数据转换 |
filter |
✅ | ❌ | 新数组 | 数据筛选 |
reduce |
✅ | ❌ | 累积值 | 聚合计算 |
for...in |
✅ | ✅ | 无 | 避免用于数组 |
高级场景
遍历时修改原数组
// 逆序遍历避免索引错乱
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === 2) arr.splice(i, 1);
}
并行遍历多个数组
const names = ["Alice", "Bob"];
const ages = [25, 30];
for (const [i, name] of names.entries()) {
console.log(`${name} is ${ages[i]} years old`);
}
掌握这些方法后,你可以根据具体需求选择最合适的遍历方式!