0

Here for the Service class I like to create a default iterator. I need to make service iterable but I can not think further. I believe I need to use *Symbol.iterator but don't know how to use

class Service {

  constructor() {
      this.link = [];
  }

}

var service = new Service();
service.link.push(1);
service.link.push(2);
service.link.push(3);

for (let x of service) {
  console.log(x);
}

1 Answer 1

3

Yes, just define *[Symbol.iterator]() { on the class

class Service {
  constructor() {
    this.link = [];
  }
  *[Symbol.iterator]() {
    for (let i = 0; i < this.link.length; i++)
      yield this.link[i];
  }
}
var service = new Service();
service.link.push(1);
service.link.push(2);
service.link.push(3);
for (const x of service) {
  console.log(x);
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.