How to make an iterator out of an ES6 class

后端 未结 6 1159
挽巷
挽巷 2021-01-30 10:21

How would I make an iterator out of an ES6 class in the same manner as JS1.7 SomeClass.prototype.__iterator__ = function() {...} syntax?

[EDIT 16:00]

<
6条回答
  •  余生分开走
    2021-01-30 11:00

    Documentation: Iteration Protocols

    Example class implementing both iterator protocol and iterable protocol techniques:

    class MyCollection {
      constructor(elements) {
        if (!Array.isArray(elements))
          throw new Error('Parameter to constructor must be array');
    
        this.elements = elements;
      }
    
      // Implement "iterator protocol"
      *iterator() {
        for (let key in this.elements) {
          var value = this.elements[key];
          yield value;
        }
      }
    
      // Implement "iterable protocol"
      [Symbol.iterator]() {
        return this.iterator();
      }
    }
    

    Access elements using either technique:

    var myCollection = new MyCollection(['foo', 'bar', 'bah', 'bat']);
    
    // Access elements of the collection using iterable
    for (let element of myCollection)
      console.log('element via "iterable": ' + element);
    
    // Access elements of the collection using iterator
    var iterator = myCollection.iterator();
    while (element = iterator.next().value)
      console.log('element via "iterator": ' + element);
    

提交回复
热议问题