0
class List{
  constructor(){
    this.data = [1,2,3];
  }

  [Symbol.iterator](){
    return this.data;
  }

}


let list = new List();
for(let i of list)
  console.log(i);

Error in the for() line:

Uncaught TypeError: undefined is not a function

So it's not possible to use iterator with our own classes like in PHP?

2
  • 2
    I think you need to return an iterator, not an iterable – return this.data[Symbol.iterator]() Commented Oct 11, 2018 at 23:42
  • I fixed it with *[Symbol.iterator](){ for(let i of this.data) yield i; } Commented Oct 11, 2018 at 23:45

2 Answers 2

2

This isn't working because you have not properly implemented the iterable protocol. For an object to be an iterable, it must have an @@iterator key (which you have), which returns an iterator, which is what you are missing (arrays are iterables but are not iterators).

However, since an array is an iterable, you can use its @@iterator property to get an iterable for it. Then you can return that instead.

class List{
  constructor(){
    this.data = [1,2,3];
  }

  [Symbol.iterator](){
    return this.data[Symbol.iterator]();
  }

}


let list = new List();
for(let i of list)
  console.log(i);

You can read more about the Javascript iterable/iterator protocol here.

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

Comments

2

You can make the the [Symbol.iterator] property of you object a generator rather than a function and just yield the list elements individually with *:

class List {
  constructor() {
    this.data = [1, 2, 3];
  }

  *[Symbol.iterator]() {
    yield* this.data;
  }

}

let list = new List();
for (let i of list) {
  console.log(i);
}

1 Comment

Ah! Ninja'd! I shall delete my answer.

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.