JS - iterator (iterator)

1. Concept

       JavaScript originally represented "collection" data structures, mainly arrays (' Array ') and objects (' Object '), and ES6 added Map and Set. In this way, there are four kinds of data sets, and users can also use them in combination to define their own data structures. For example, the members of an array are Maps, and the members of a Map are objects. This requires a unified interface mechanism to handle different data structures.
       Iterator is such a mechanism. It is an interface that provides an access mechanism for different data structures, the for...of loop. When using for...ofa loop to traverse a certain data structure, the loop will automatically look for the Iterator interface. As long as any data structure deploys the Iterator interface, the traversal operation can be completed (that is, all members of the data structure are processed in turn).

2. Essence 

        An iterator object is essentially a pointer object. Through the next() of the pointer object, it is used to move the pointer.
       
Iterator protocol: The object must provide a next(), which either returns the next item of the iteration or causes a Stopiteration exception to terminate the iteration.
        Every time the next () method is called, an object will be returned, and the information of the current member of the data structure will be returned. This object has two attributes, value and done. The value attribute returns the member at the current position. The done attribute is a Boolean value indicating whether the traversal is over, that is, whether it is necessary to call next () again. For traversers, both the value: undefined and done: false attributes can be omitted.
        
ES6 stipulates that the default Iterator interface is deployed on the Symbol.iterator property of the data structure; in other words, as long as a data structure has the Symbol.iterator property, it is considered traversable.

3. Native objects that implement the Iterator interface

The data structures that natively have the Iterator interface are:

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • the arguments object of the function
  • NodeList object

 You can see that the Array prototype object has implemented the Iterator property:

 Then the instance object of the array also has this property, you can call it to try:

The following is an example of mocking the return of the next() method:

       The above code defines a makeIterator function, which is a function generated by a traverser, and its function is to return a traverser object. Executing this function on the array ['a', 'b'] will return the traverser object (pointer object) it of the array . Pointer object nextmethods used to move the pointer. At the beginning, the pointer points to the beginning of the array. Then, each time nextthe method is called, the pointer will point to the next member of the array. The first call, points to a; the second call, points to b.
        In short, calling the next() method of the pointer object can traverse the given data structure in advance.
        As mentioned above, for the traverser object, both done: false and value: undefined properties can be omitted, so the above makeIteratorfunction can be abbreviated into the following form.

 Use occasions:

① Deconstruct and assign values ​​to the data that implements the Iterator interface

 ② Spread operator

The extension operator of the above code calls the Iterator interface internally.

In fact, this provides a convenient mechanism to convert any data structure that implements the Iterator interface into an array. In other words, as long as a data structure implements the Iterator interface, you can use the spread operator on it to convert it into an array.

3. The for...of loop

for...ofLoops can work with arrays, Set and Map structures, certain array-like objects (such as argumentsobjects, DOM NodeList objects), strings, and more.

The array has an iterator interface natively (the Symbol.iterator property is deployed by default), and the for...of loop is essentially the traverser generated by calling this interface:

const arr = ['red', 'green', 'blue'];

for(let v of arr) {
  console.log(v); // red green blue
}

const obj = {};
obj[Symbol.iterator] = arr[Symbol.iterator].bind(arr);

for(let v of obj) {
  console.log(v); // red green blue
}

In the above code, the empty object objdeploys the properties arrof the array Symbol.iterator, and the loop objof the result for...ofproduces arrexactly the same result.

The for ... of loop can replace the array instance forEach method.

const arr = ['red', 'green', 'blue'];

arr.forEach(function (element, index) {
  console.log(element); // red green blue
  console.log(index);   // 0 1 2
});

JavaScript's original for...inloop can only get the key name of the object, and cannot directly get the key value. ES6 provides for...ofloops, allowing traversal to obtain key values.

var arr = ['a', 'b', 'c', 'd'];

for (let a in arr) {
  console.log(a); // 0 1 2 3
}

for (let a of arr) {
  console.log(a); // a b c d
}

Four, Set and Map structure

The Set and Map structures also natively have the Interator interface, which can directly use the for...of loop.

var engines = new Set(['1','2','3']);
for (var e of engines) {
  console.log(e);   // 1  2  3
} 

var class = new Map();
class .set('Tom', 12);
class .set('Lala', 13);
class .set('9300', 14);
for (var [name,value] of class) {
  console.log(name + ':' + number);    // Tom:12  Lala:13  9300:14
}     

The above code demonstrates how to traverse the Set and Map structures. It should be noted that the order of traversal first is the order in which the older members are added to the data structure. Secondly, when the Set structure is traversed, a value is returned. When the Map structure is traversed, an array is returned, and the two members of the array are the key name and key value of the current Map member.

let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
  console.log(pair);
}
// ['a', 1]
// ['b', 2]

for (let [key, value] of map) {
  console.log(key + ' : ' + value);
}
// a : 1
// b : 2

For other content, please refer to  Getting Started with ES6

Guess you like

Origin blog.csdn.net/m0_52545254/article/details/126741625