A deep understanding of the JavaScript series (35): a detailed explanation of the design pattern iterator Pattern
This article mainly introduces a deep understanding of the JavaScript series (35): The Design Pattern describes the Iterator pattern, and the Iterator pattern (Iterator): provides a method to sequence each element in an aggregate object, without exposing the internal representation of this object, you can refer
Introduction
Iterator: provides a method to sequentially aggregate elements of an object without exposing the internal representation of the object.
The iterator has the following features:
1. Access the content of an aggregate object without exposing its internal representation.
2. provides a unified interface for Traversing different set structures, so that the same algorithm can be operated on different set structures.
3. changing the structure of the set where the iterator is located during traversal may cause problems (for example, items cannot be modified in C #'s foreach ).
Body
In general iteration, we must have at least two methods, hasNext () and Next (), to traverse all objects. Let's give an example:
The Code is as follows:
Var callback = (function (){
Var index = 0,
Data = [1, 2, 3, 4, 5],
Length = data. length;
Return {
Next: function (){
Var element;
If (! This. hasNext ()){
Return null;
}
Element = data [index];
Index = index + 2;
Return element;
},
HasNext: function (){
Return index <length;
},
Rewind: function (){
Index = 0;
},
Current: function (){
Return data [index];
}
};
}());
The usage is the same as that in C:
The Code is as follows:
// The result of iteration is: 1, 3, 5
While (iterator. hasNext ()){
Console. log (summary. next ());
}
Of course, you can reset the data in an additional way and continue with other operations:
The Code is as follows:
// Reset
Response. rewind ();
Console. log (summary. current (); // 1
JQuery application example
A very famous iterator in jQuery is the $. each method. With each, we can pass in additional functions and perform iterative operations on all item items, for example:
The Code is as follows:
$. Each (['dududu', 'dududu', 'yogurt girl ', 'Mm'], function (index, value ){
Console. log (index + ':' + value );
});
// Or
$ ('Lil'). each (function (index ){
Console. log (index + ':' + $ (this). text ());
});
Summary
The application scenario of the iterator is: if the internal results of the set are often different, we do not want to expose its internal structure, but it makes the client code transparent to access the elements, in this case, we can use the iterator mode.