Iterator คือออบเจกต์ที่มีเมธอด next() ซึ่งส่งกลับ ออบเจกต์คือ ถ้ามีเมธอด — นั่นคือสิ่งที่ทำให้ และ spread ทำงาน () เป็นวิธีที่สะดวกในการสร้าง iterator ที่สามารถ ด้วย
Iterator คือออบเจกต์ที่มีเมธอด next() ซึ่งส่งกลับ ออบเจกต์คือ ถ้ามีเมธอด — นั่นคือสิ่งที่ทำให้ และ spread ทำงาน () เป็นวิธีที่สะดวกในการสร้าง iterator ที่สามารถ ด้วย
{ value, done }[Symbol.iterator]for...offunction*yieldfunction* idGenerator() {
let id = 1;
while (true) { // infinite, but lazy — only computes on demand
yield id++; // pause here, return a value, resume on next()
}
}
const gen = idGenerator();
gen.next().value; // 1
gen.next().value; // 2 — execution resumed where it paused
แนวคิดหลัก: การดำเนินการ หยุดชั่วคราว ที่ yield แต่ละครั้ง และ ดำเนินการต่อ ที่ .next() ครั้งถัดไป โดยรักษาสถานะภายในระหว่างการเรียก ไม่มีการคำนวณอะไรจนกว่าคุณจะขอมัน
// process a huge/infinite sequence without building it all in memory
function* take(iterable, n) {
let i = 0;
for (const x of iterable) {
if (i++ >= n) return;
yield x;
}
}
[...take(idGenerator(), 3)]; // [1, 2, 3] — from an infinite generator
const range = {
from: 1, to: 3,
*[Symbol.iterator]() { for (let i = this.from; i <= this.to; i++) yield i; },
};
[...range]; // [1, 2, 3] — works with for...of and spread
Generator เปิดใจให้กับลำดับแบบ lazy/อนันต์ การวนซ้ำแบบกำหนดเอง และการสตรีมแบบประหยัดหน่วยความจำ
พวกมันยังเป็นพื้นฐานของไลบรารี async ในช่วงแรก (co) และอยู่เบื้องหลังการวนซ้ำ async (for await...of)
โปรโตคอล iterator คือสิ่งที่รวม for...of, spread และการ destructuring เข้าด้วยกันในอาร์เรย์ Maps Sets และสตริง