Answer the question
In order to leave comments, you need to log in
Are these iterators equivalent?
There are 2 iterable objects: a string and a custom one. In the custom one, the iter() method is called first, and then the next() method is called several times. as a result, all elements of the custom iterable object are displayed:
class Obj {
constructor(word) {
this.word = word;
}
iter() { return new Iterator(this.word); }
}
class Iterator {
constructor(word) {
this.word = word;
this.index = 0;
}
next() {
try {
let letter = this.word[this.index];
this.index += 1;
return letter;
} catch (err) {
throw "StopIteration";
}
}
iter() { return this; }
}
const obj = new Obj('sergey');
it = obj.iter();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
for of
const s = 'sergey';
for (let char of s) {
console.log(char);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question