一、定義
for...of
是 ES6(ECMAScript 2015)引入的一種用于 遍歷可迭代對象(Iterable)的循環語句
二、語法
for (const item of iterable) {// 代碼塊
}
?參數:
iterable
:一個可迭代對象(如數組、字符串、Set、Map等)。item
:當前迭代的值。
三、舉例
const arr = [10, 20, 30];
for (const value of arr) {console.log(value);
}
// 輸出:10, 20, 30
?相比 forEach
,for...of
支持 break
和 continue
:
for (const value of arr) {if (value === 20) continue;console.log(value);
}
// 輸出:10, 30
四、使用
遍歷 Set
Set
是無重復值的集合,for...of
可用于遍歷:
const mySet = new Set(["a", "b", "c"]);
for (const value of mySet) {console.log(value);
}
// 輸出:a, b, c
遍歷 Set
for...of
默認遍歷 Map
的鍵值對:
const myMap = new Map([["name", "Alice"],["age", 25]
]);for (const [key, value] of myMap) {console.log(key, value);
}
// 輸出:name Alice
// age 25
遍歷 arguments
對象
function test() {for (const arg of arguments) {console.log(arg);}
}
test(1, 2, 3);
// 輸出:1, 2, 3
?五、名詞解釋
1、什么是可迭代對象(Iterable)?
可迭代對象是 實現了 Symbol.iterator
方法 的對象,這意味著它可以被 for...of
遍歷。
常見的可迭代對象:
-
數組(Array)
-
字符串(String)
-
Set
-
Map
-
arguments
對象 -
NodeList(DOM API 返回的集合)
-
TypedArray(比如
Uint8Array
) -
生成器(Generator)
比喻:
symbol.iterator
就像書的“書簽功能”?想象你有一本書這本書就是一個對象,而書簽就是
Symbol.iterator
。普通的對象(沒有
Symbol.iterator
)就像一本沒有書簽的書,你只能自己翻頁,不知道讀到哪里了,也不能按順序自動閱讀。比如:
const obj = { a: 1, b: 2 }; for (const item of obj) { // ?報錯:obj 不是可迭代對象 console.log(item); }
普通對象
{}
不能直接用for...of
,因為它沒有“書簽功能”。數組(自帶
Symbol.iterator
)而數組
[]
、字符串"abc"
等天生帶有書簽功能(Symbol.iterator
),你可以一頁一頁順序讀下去:
const arr = [10, 20, 30]; for (const num of arr) { console.log(num); // ?輸出 10, 20, 30 }
?數組可以
for...of
遍歷,因為它天生有Symbol.iterator
(書簽功能)。
2、arguments
對象是什么?
在 JavaScript 里,arguments
是一個“類數組”對象(array-like object),用來存儲所有傳遞給函數的參數。
簡單來說,當你調用一個函數時,所有參數都會被存到 arguments
里,即使你沒有在函數的參數列表中定義它們。
function test() {console.log(arguments); // arguments 是個對象
}test(1, 2, 3, 'hello');
[Arguments] { '0': 1, '1': 2, '2': 3, '3': 'hello' }
從 ES6 開始,arguments
已經不推薦使用,因為它不是數組,很多數組方法不能直接用。
我們應該用剩余參數(Rest 參數) ...args
,它會直接生成數組:
注意args是變量名寫什么都行
function test(...args) {for (const arg of args) {console.log(arg);}
}test('a', 'b', 'c');
// 輸出:
// a
// b
// c
?六、實戰
function sum(...nums) {return nums.reduce((a, b) => a + b, 0);
}console.log(sum(10, 20, 30)); // 60
console.log(sum(1, 2, 3, 4, 5)); // 15
就是相當于把傳入的值自動組成一個數組