1. for of 循环
作用:
遍历可迭代对象(如数组、字符串、Map、Set 等)的值。
特点:
- 直接获取元素的值,而非索引或键。
- 支持 break 、 continue 中断循环。
- 不能直接遍历对象(普通对象不可迭代,需配合 Object.keys() 等)。
示例:
const arr = [10, 20, 30];
for (const value of arr) {
console.log(value); // 10、20、30
if (value === 20) break; // 可中断循环
}
// 遍历字符串
const str = "hello";
for (const char of str) {
console.log(char); // h、e、l、l、o
}
2. for in 循环
作用:
遍历对象的可枚举属性(包括继承的属性),或数组的索引。
特点:
- 主要用于遍历对象,获取属性名;遍历数组时获取索引(字符串类型)。
- 会遍历原型链上的属性,需用 hasOwnProperty() 过滤自身属性。
- 支持 break 、 continue 中断循环。
示例:
// 遍历对象
const obj = { name: "Tom", age: 18 };
for (const key in obj) {
// 过滤继承的属性
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]); // name Tom、age 18
}
}
// 遍历数组(不推荐,索引是字符串)
const arr = [10, 20, 30];
for (const index in arr) {
console.log(index, arr[index]); // 0 10、1 20、2 30(index 是字符串 "0"、"1" 等)
}
3. forEach 方法
作用:
数组的内置方法,用于遍历数组的每个元素。
特点:
- 仅适用于数组(或类数组对象),接收回调函数,参数为 (value, index, array) 。
- 无法用 break 、 continue 中断循环( return 仅跳过当前次循环)。
- 没有返回值(默认返回 undefined )。
示例:
const arr = [10, 20, 30];
arr.forEach((value, index, array) => {
console.log(value, index); // 10 0、20 1、30 2
if (value === 20) return; // 仅跳过当前次,不会中断整个循环
});
最佳实践
- 遍历数组/字符串的值:优先用 for of 。
- 遍历对象的属性:用 for in 并配合 hasOwnProperty() 。
- 数组简单遍历且不需要中断:用 forEach (代码更简洁)。
- 需中断循环时,避免用 forEach ,选择 for of 或普通 for 循环。