MENU
User defined Iterables
As a generator function returns an iterator, you can conveniently define the [Symbol.iterator] method as a generator function instead.
class AnimalsList {
constructor(...args) {
this.index = -1;
this.animals = args;
}
*[Symbol.iterator]() {
while (this.index < this.animals.length - 1) {
this.index++;
yield this.animals[this.index];
}
}
}
var myAnimals = new AnimalsList('Brownie', 'Greenie', 'Lucky', 'Spotty');
for (let v of myAnimals) console.log(v);Brownie
Greenie
Lucky
Spotty
At the time of writing, Array.prototype.values() is not supported by browsers. In the future, you may do the following instead:
class AnimalsList {
constructor(...args) {
this.animals = args;
}
*[Symbol.iterator]() {
return this.animals.values();
}
}