Custom Iterators With For Of Protocol
Implement Symbol.iterator so your own objects work with for-of, spread, and destructuring — the same protocol as built-in collections.
Code
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
// Symbol.iterator:让对象可直接 for-of / 展开 / 解构
*[Symbol.iterator]() {
for (let value = this.start; value <= this.end; value += 1) {
yield value;
}
}
}
const range = new Range(3, 7);
console.log('for-of:', [...range]);
console.log('spread sum:', [...range].reduce((a, b) => a + b, 0));
const [first, , third] = new Range(10, 12);
console.log('destructured:', first, third);
// 生成器本身也可直接迭代
function* pairs(entries) {
for (const [key, value] of Object.entries(entries)) yield key + '=' + value;
}
console.log('pairs:', [...pairs({ a: 1, b: 2 })]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
for-of: [ 3, 4, 5, 6, 7 ]
spread sum: 25
destructured: 10 12
pairs: [ 'a=1', 'b=2' ]How the snippet works
Structurally, expect the class Range and nothing else.
for (let value = this.start; value <= this.end; value += 1) and for (const [key, value] of Object.entries(entries)) yield key + '=' + value; nest, one inside the other.
Module-level bindings hold the data — range — with no function scope in between.
Applying it
The demo output is labeled (for-of:, spread sum:, destructured:), so every printed line maps back to its originating operation.
Statements that matter
for (const [key, value] of Object.entries(entries)) yield key + '=' + value;
for (let value = this.start; value <= this.end; value += 1) {
yield value;
}
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `range`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.