js-ES6 study notes -Iterator

1, walker (the Iterator) is an interface that provides a unified mechanism for access to a variety of different data structures. Any data structure as long as the deployment Iterator interface, to complete traversal operation (i.e., sequentially processed all members of the data structure).

2, the Iterator role has three: one for the various data structures, to provide a unified, easy-access interface; second is to make members of the data structure can be arranged in a certain order; the third is ES6 created a new traversal command for...ofcycle, Iterator interface is mainly for for...ofconsumption.

3, in ES6, some native data structure includes Iterator interface (such as arrays), i.e. without any treatment, can be for...ofloop through, and some will not (such as object). The reason is that these data structures deployed native Symbol.iteratorproperties (see below), a number of additional data structures not. Those who deployed Symbol.iteratorattribute data structure, called the deployment a traversal interface. Call this interface, it will return a visitor object.

4, in ES6, there are three classes of data structures native Iterator interface includes: array, some of the array-like objects, Set, and Map structures.

5, an example of adding the Iterator interface object.

let obj = {
  data: [ 'hello', 'world' ],
  [Symbol.iterator]() {
    const self = this;
    let index = 0;
    return {
      next() {
        if (index < self.data.length) {
          return {
            value: self.data[index++],
            done: false
          };
        } else {
          return { value: undefined, done: true };
        }
      }
    };
  }
};

6, the following is an array of array-like object calls the Symbol.iteratorexample of the method.

let iterable = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3,
  [Symbol.iterator]: Array.prototype[Symbol.iterator]
};
for (let item of iterable) {
  console.log(item); // 'a', 'b', 'c'
}

Note that ordinary objects to deploy an array of Symbol.iteratormethods, there is no effect.

7, there are some occasions call Iterator interface by default (ie Symbol.iteratormethod), the following will be introduced in addition to the for...ofcycle, there are several other occasions.

  • Deconstruction assignment
  • Extended operator (...)
  • yield * _yield * behind with a traversable structure, it calls to traverse the interface structure.
  • Due to iterate calls traverse the interface, so any occasions to accept arrays as parameters, in fact, call

8, a string-like object is an array, also having a native Iterator interface.

9, in addition to traversing the object nextmethod, it may also have returnmethods and throwmethods. If you write your own visitor object generating function, it nextis to be deployed, returnmethods, and throwwhether the method of deployment is optional.

Guess you like

Origin www.cnblogs.com/pwindy/p/12635258.html