Iteration
suggest changeA generator is iterable. It can be looped over with a for...of statement, and used in other constructs which depend on the iteration protocol.
function* range(n) {
for (let i = 0; i < n; ++i) {
yield i;
}
}
// looping
for (const n of range(10)) {
// n takes on the values 0, 1, ... 9
}
// spread operator
const nums = [...range(3)]; // [0, 1, 2]
const max = Math.max(...range(100)); // 99
A generator can also be an object's iterator. function* below yields the object's own values:
const user = {
name: "sam", totalReplies: 17, isBlocked: false
};
user[Symbol.iterator] = function *(){
const properties = Object.keys(this);
for(const p of properties){
yield this[p];
}
};
for(const p of user){
console.log( p );
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents