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...of
cycle, Iterator interface is mainly for for...of
consumption.
3, in ES6, some native data structure includes Iterator interface (such as arrays), i.e. without any treatment, can be for...of
loop through, and some will not (such as object). The reason is that these data structures deployed native Symbol.iterator
properties (see below), a number of additional data structures not. Those who deployed Symbol.iterator
attribute 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.iterator
example 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.iterator
methods, there is no effect.
7, there are some occasions call Iterator interface by default (ie Symbol.iterator
method), the following will be introduced in addition to the for...of
cycle, 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 next
method, it may also have return
methods and throw
methods. If you write your own visitor object generating function, it next
is to be deployed, return
methods, and throw
whether the method of deployment is optional.