Iterator is a mechanism (interface) that provides a unified access mechanism for various data structures. Any data structure can be iterated as long as the Iterator interface is deployed, and all members of the data structure can be processed in turn

2. Instances of iterators

+ members that have the next method to iterate over the data structure in turn + the result of each iteration is an object {done:false,value: XXX} + done: indicates whether the iteration is complete + value: indicates the result of the current iterationCopy the code

3. Data structures (values) that have symbol. iterator properties are said to be traversable and can be processed based on a for of loop

* * + + array part class array: the arguments/NodeList/HTMLCollection... * + String * + Set * + Map * + generator object * + ... The * * object does not have symbol. iterator by default and is an uniterable data structureCopy the code

4. Write an Interator class by hand

class Iterator { constructor(assemble) { let self = this; self.assemble = assemble; self.index = 0; } next() { let self = this; if (self.index > self.assemble.length - 1) { return { done: true, value: undefined }; } return { done: false, value: self.assemble[self.index++] }; } // call /* let itor = new Iterator([10, 20, 30, 40]); console.log(itor.next()); console.log(itor.next()); console.log(itor.next()); console.log(itor.next()); console.log(itor.next()); // for for loop is a loop that iterates through each item in the set according to the specification of the iterator. Each iteration finds some property in the set: Iterator: "Objects that have this property belong to objects that can be iterated over in order to use the for of loop, // + let itor=arr[symbol.iterator]() // + itor.next() -> {done:false,value: XXX} // +... // + done determines whether the loop executes the value of value to itemCopy the code

5, What does interator do

Array.prototype[symbol.iterator] = function () {// this->arr let self = this, index = 0; return { next() { if (index > self.length - 1) { return { done: true, value: undefined }; } return { done: false, value: self[index++] }; }}; };Copy the code

6. Combine the Interator interface to encapsulate Symbol. Interator method

Array.prototype[Symbol.iterator] = function () {
    return new Iterator(this);
};
Copy the code

Is it possible to iterate over objects directly based on “for of”?

Iterator let obj = {0: 1, 1: 2, 2: 3, length: 3, // [Symbol. Iterator]: Array.prototype[Symbol.iterator] [Symbol.iterator]: function () { return new Iterator(this); }}; for (let item of obj) { console.log(item); }Copy the code