可迭代物件是物件上實現了 iterable protocol - 可迭代協議 的物件,且可以使用build-ins語法進行迭代,例如 for (let i in iterable)、 [...iterable]。
⚠️注意: 使用這些build-ins語法必須是物件上實現了可迭代協議不是迭代器協議,否則對物件迭代將會丟擲異常:
❌ Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
at <anonymous>:1:1
複製程式碼
目前有很多JavaScript內建對資料集合已經實現了迭代器協議,有:
Array
const iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value); // 10 20 30
}
複製程式碼
String
const iterable = 'boo';
for (const value of iterable) {
console.log(value); // 'b''o''o'
}
複製程式碼
const gen = (function *(){
yield 1;
yield 2;
yield 3;
})();
for (const o of gen) {
console.log(o);
break; // Closes iterator
}
// The generator should not be re-used, the following does not make sense!
for (const o of gen) {
console.log(o); // Never called.
}
複製程式碼