Iterator Concept
Iterator is an interface that provides a unified access mechanism for a variety of data structures. Any data structure can be traversed as long as the iterator interface is deployed (that is, the member that processes the data structure at a time).
Handwriting Iterator interface:
Handwriting Iterator interface
function iterator (arr) {let
index=0;
return{
next:function () {
return index<arr.length?{ Value:arr[index++],done:false}:{value:undefined,done:true}}}
}
const arr=[1, ' OK ', 2];
Const It=iterator (arr);
Console.log (It.next ());//{value:1, done:false}
Console.log (It.next ());//{value: "OK", done:false}
Console.log (It.next ());//{value:2, done:false}
Console.log (It.next ());//{value:undefined, done:true}
Console.log (It.next ());//{value:undefined, done:true}
Iterator Interface
The default iterator interface is deployed in the Symbol.iterator property of the data structure, and the Symbol.iterator property itself is also a function, which is the default traversal generator function for the current data structure. Executes this function, it returns a walker.
The data structure of the native iterator interface is as follows:
1) Array
2) Map
3) Set
4) String
5) TypedArray
6) Argument object of the function
For data structures that have a iterator interface deployed, you can use a for loop.
For the Loop
Const ofarr=[1,2,3];//array for
(let I of Ofarr) {
console.log (i)
}
//SET data structure
const Set=new Set ([' A ', ' B ', ' C ']);
For (let item of Set) {
Console.log (item);
}
Map data Structure
const map=new Map ([[' A ', 1],[' B ', 2],[' C ', 3]]);
For (let data of map) {
console.log (data)
} for
(let [key,value] of map) {//struct assignment
console.log (key, value);
}
All structures with Symbol.iterator properties have iterator interface
Const arr=[1,2,3];
Const set=new Set ([' A ', ' B ', ' C ']);
Const map=new Map ([[' A ', 1]]);
Const Itarr=arr[symbol.iterator] ();
Const Itset=set[symbol.iterator] ();
Const Itmap=map[symbol.iterator] ();
Console.log (arr)
Console.log (Itarr)
Console.log (set)
Console.log (itset)
console.log (map)
Console.log (Itmap)
Console.log (Itset.next ());
Console.log (Itset.next ());
Console.log (Itset.next ());
Console.log (Itset.next ());
Console.log (Itset.next ());