js实现forof
for...of 循环的基本用法
for...of 循环用于遍历可迭代对象(如数组、字符串、Map、Set 等),直接获取值而非索引。
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item); // 输出: 1, 2, 3
}
遍历字符串
字符串是可迭代对象,可以逐字符遍历:
const str = "hello";
for (const char of str) {
console.log(char); // 输出: h, e, l, l, o
}
遍历 Map 和 Set
Map 和 Set 也是可迭代对象:
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
console.log(key, value); // 输出: a 1, b 2
}
const set = new Set([1, 2, 3]);
for (const val of set) {
console.log(val); // 输出: 1, 2, 3
}
与 for...in 的区别
for...of 遍历值,for...in 遍历键(或属性名):
const arr = [10, 20, 30];
for (const index in arr) {
console.log(index); // 输出: 0, 1, 2(字符串类型)
}
for (const value of arr) {
console.log(value); // 输出: 10, 20, 30
}
提前终止或跳过
使用 break 终止循环或 continue 跳过当前迭代:
const nums = [1, 2, 3, 4, 5];
for (const num of nums) {
if (num === 3) break;
console.log(num); // 输出: 1, 2
}
自定义可迭代对象
实现 Symbol.iterator 方法使对象支持 for...of:

const myIterable = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
yield 3;
}
};
for (const val of myIterable) {
console.log(val); // 输出: 1, 2, 3
}






