Through the Iterator
An Iterator is an interface that provides a uniform access mechanism for various data structures. Any data structure can be traversed by deploying the Iterator interface
Iterator has three functions:
- Provide a unified and simple access interface for various data structures;
- Enable the members of a data structure to be arranged in a certain order;
- ES6 creates a new traversal command for… Of loop, Iterator interface for… Of consumption
Iterator implementation process
Creates a pointer object that points to the beginning of the current data structure. Each call to the next method returns information about the current member of the data structure. Returns an object containing the value and done properties. The value attribute is the value of the current member, and the done attribute is a Boolean that indicates whether the traversal is complete. If done is false, the traversal is not complete.
var arr = [1.3.5.7.9];
var iter = arr[Symbol.iterator]();
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());`
Copy the code
ES6 iterable data types
ES6 specifies that the default Iterator interface is deployed in the Symbol. Iterator property of the data structure (an object is considered “traversable” as long as it has the Symbol. The default Iterator interface is Array, Map, Set, String, TypedArray, arguments for functions, and NodeList
An easy way to deploy the Iterator interface for array-like objects (with numeric keys and length attributes) is to refer directly to the array’s Iterator interface in the Symbol
var obj2 = { // An array-like object with an ordered number property name
0:1.1:2.length:2[Symbol.iterator]:Array.prototype[Symbol.iterator]
};
for (let i of obj2){
console.log(i);
};
Copy the code
for… of
Any data that has an iterator interface can be used for… Iterator methods are deployed on the Symbol. Iterator property
for… Of iterates over all “ordered” data structures. Since object is an unordered object, this method cannot be used.