Reputation: 12506
Node.js v10.11.0
Why iteration doesn't happen in my code?
'use strict';
const stuff = Object.create(null)
stuff.items = ['a','b','c','d']
stuff[Symbol.iterator] = function*(){
return this.items[Symbol.iterator]()
}
for(let n of stuff){
console.log(n) // It doesn't happen
}
Upvotes: 1
Views: 33
Reputation: 191996
Set the stuff
iterator to be the items
iterator:
const stuff = Object.create(null)
stuff.items = ['a','b','c','d']
stuff[Symbol.iterator] = stuff.items[Symbol.iterator].bind(stuff.items);
for(let n of stuff){
console.log(n) // It doesn't happen
}
Upvotes: 1
Reputation: 138307
Your generator function does not yield
anything, you only return another iterator but the return value is ignored in a for..of. Instead you either yield the entries of the other iterator:
stuff[Symbol.iterator] = function*(){
yield* this.items[Symbol.iterator]();
};
or you turn the generator function into a regular one (remove the *
):
stuff[Symbol.iterator] = function() {
return this.items[Symbol.iterator]();
};
Upvotes: 1