1. 传统 for 循环
const arr = [10, 20, 30];
for (let i = 0; i < arr.length; i++) {
console.log(`索引 ${i}: 值 ${arr[i]}`);
}
// 输出:
// 索引 0: 值 10
// 索引 1: 值 20
// 索引 2: 值 30
特点:最基础的循环,可通过索引精准控制
适用场景:需要索引操作、复杂循环控制(如
break
/continue
)注意:冗长但灵活性最高
2. for...of 循环 (ES6)
const fruits = ['🍎', '🍌', '🍊'];
for (const fruit of fruits) {
if (fruit === '🍌') break; // 支持中断
console.log(fruit);
}
// 输出: 🍎
特点:直接获取值(非索引),支持
break
/continue
适用场景:数组、字符串、Map/Set等可迭代对象
注意:不能遍历普通对象(会报错)
3. for...in 循环
const person = { name: 'Alice', age: 25 };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// 输出:
// name: Alice
// age: 25
特点:遍历对象键名(包括原型链上的可枚举属性)
适用场景:遍历对象属性,数组可用但不推荐(会遍历非数字键)
注意:用
hasOwnProperty
过滤原型属性
4. forEach 方法
[1, 2, 3].forEach((num, index) => {
console.log(num * index);
});
// 输出:0 (1*0), 2 (2*1), 6 (3*2)
特点:数组专用,为每个元素执行回调
适用场景:简单遍历数组,无需中断的场景
注意:无法用
break
中断,返回值始终为undefined
5. map 方法
const nums = [1, 2, 3];
const squares = nums.map(num => num * num);
console.log(squares); // [1, 4, 9]
特点:返回新数组(原数组不变),元素是一一映射的结果
适用场景:数据转换(如 API 响应格式化)
注意:回调必须
return
,否则新数组元素为undefined
6. filter 方法
const numbers = [10, 15, 20, 25];
const bigNumbers = numbers.filter(num => num > 15);
console.log(bigNumbers); // [20, 25]
特点:返回通过测试的元素组成的新数组
适用场景:数据筛选(如过滤无效值)
注意:不会修改原数组
🔑 核心区别总结表
方法 | 主要用途 | 返回值 | 能否中断循环 | 适用数据类型 |
---|---|---|---|---|
for |
通用循环 | 无 | ✅ | 数组、字符串 |
for...of |
遍历可迭代对象的值 | 无 | ✅ | 数组、字符串、Map/Set |
for...in |
遍历对象键名 | 无 | ✅ | 对象 |
forEach |
数组遍历 | undefined |
❌ | 数组 |
map |
数组元素转换 | 新数组 | ❌ | 数组 |
filter |
数组元素筛选 | 新数组 | ❌ | 数组 |
💡 黄金实践建议
遍历数组:
需要索引 →
for
或forEach
只需值 →
for...of
需返回新数组 →
map
/filter
遍历对象 → 只用
for...in
(记得用obj.hasOwnProperty(key)
过滤)特殊需求:
需要中断循环 →
for
/for...of
操作DOM集合 → 先用
Array.from()
转数组再用数组方法
⚠️ 避免用
for...in
遍历数组!它会遍历非数字键和原型链属性,导致意外行为。