Andrey Bushman
Andrey Bushman

Reputation: 12506

iteration through Symbol.iterator doesn't happen

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

Answers (2)

Ori Drori
Ori Drori

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

Jonas Wilms
Jonas Wilms

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

Related Questions