Iterators and Generators
iteration protocol, 自定义 iterables, generator 函数, and lazy 数据序列.
你将学到
- iterable and iterator protocols (Symbol.iterator)
- 创建自定义 iterable 对象
- Generator 函数使用函数* and yield
- Lazy evaluation and 无限序列
- Delegating 使用 yield* and two-方式 communication 通过 yield
概念讲解
The Iteration Protocol
An iterable is any object with a [Symbol.iterator] method that returns an iterator. An iterator is an object with a 下一个() method that returns { 值, 做 }. When you use for...的, the spread operator, or destructuring, JavaScript calls [Symbol.iterator] and repeatedly calls 下一个() until 做 is true. Arrays, strings, Maps, and Sets are all built-in iterables.
Custom Iterables
You can make any object iterable by defining [Symbol.iterator] as a method that returns an iterator. This lets your custom objects work with for...的, spread, and 数组.从() without inheriting from Array. The iterator's 下一个() computes each value on demand, which means you can model sequences that are too large or infinite to store in an array.
Generator Functions
A generator is a function declared with 函数* that can pause and resume. The yield keyword produces a value and suspends execution; calling 下一个() resumes from where it left off. Generators are a concise way to write iterators — the engine handles the { 值, 做 } bookkeeping for you. Each yield becomes one step of the sequence.
Lazy and Infinite Sequences
Because generators compute values on demand, they can represent infinite sequences. A generator for natural numbers never finishes, but you can take the first N with a helper. This laziness avoids allocating a huge array up front and is the basis of efficient pipelines in libraries like RxJS. Values are produced only when consumed.
yield* Delegation
yield* delegates to another iterable or generator, flattening nested sequences. You can also send values back into a generator: const input = yield output receives whatever is passed to next(value). This two-way communication makes generators powerful enough to implement cooperative multitasking and coroutines, though async/await has largely replaced that use case.
Practical Relevance
You will most often encounter iterators through built-in iterables and the for...的 loop. Writing custom generators is useful for paginated data, tree traversal, custom range objects, and any scenario where you want lazy, on-demand production of values. Understanding the protocol also demystifies how for...的 and spread work under the hood.
示例代码
// Custom iterable: a range of numbers
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
},
};
},
};
console.log([...range]); // [1, 2, 3, 4, 5]
for (const n of range) console.log("range:", n);
// Generator: lazy infinite sequence of natural numbers
function* naturalNumbers() {
let n = 1;
while (true) yield n++;
}
// Take the first N from any iterable
function take(iterable, count) {
const result = [];
for (const value of iterable) {
result.push(value);
if (result.length >= count) break;
}
return result;
}
console.log("First 5 naturals:", take(naturalNumbers(), 5)); // [1, 2, 3, 4, 5]
// Generator with yield* delegation (flatten)
function* flatten(arr) {
for (const item of arr) {
if (Array.isArray(item)) yield* flatten(item);
else yield item;
}
}
const nested = [1, [2, [3, 4]], 5];
console.log("Flattened:", [...flatten(nested)]); // [1, 2, 3, 4, 5]
// Two-way communication: send values into a generator
function* accumulator() {
let total = 0;
while (true) {
const input = yield total;
total += input;
}
}
const acc = accumulator();
acc.next(); // prime the generator
console.log(acc.next(10).value); // 10
console.log(acc.next(20).value); // 30
console.log(acc.next(5).value); // 35
Shows 自定义 iterable 范围, lazy 无限 naturalNumbers generator, take helper, yield* delegation 到 flatten nested 数组, and two-方式 communication 发送值 到 generator accumulator.
动手试一试
- 文本计数器
Counting 是 classic iteration 任务 — generators 能 produce 令牌 lazily.
- 行 Deduplicator
Iterating and deduplicating 行 benefits 从自定义 iterables.
常见错误
错误写法
Forgetting 那个 generator 必须是 primed 使用下一个() 之前发送值
正确做法
首先下一个() call 运行 generator 上到 首先 yield and cannot 发送值. Call gen.下一个() 一次到 prime 它, 然后 use gen.下一个(值) 到发送 subsequent 值到 yield.
错误写法
Trying 到 spread 无限 generator 到数组
正确做法
Spreading [...gen] calls 下一个() 直到做 是真. 无限 generator 从不 finishes, 所以这个 hangs. Use take() helper or for...的循环使用 break 到 consume 有限数字的 值.
相关资源
相关速查表
- JavaScript Cheatsheet
Iterator protocol, generator 语法, and yield/yield* 模式.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。