The definition of an iterator pattern: Provides a way to access individual objects in an aggregated object. You can do not care about the internal structure of the object, or you can sequentially access each Harajuku.
Internal iterator: External only requires one initial call
1 vareach =function(ary, callback) {2 for(vari = 0; i < ary.length; i++) {3 Callback.call (Ary[i], I, ary[i]);4 };5 }6 7 //This call was made only once.8Each ([1, 2, 3],function(i, n) {9 //doing an array of operationsTen});
External iterators: Explicit iterations must be made externally
1 //implementation of external iterators, specific customer actions not written here.2 variterator =function(ary) {3 varCurrent = 0;4 5 varNext =function(){6current++;7 };8 9 varIsDone =function(){Ten returnCurrent >=ary.length; One }; A - varGetCurrent =function(){ - returnary[current]; the }; - - //since closures are generated here, the returned object method can still be accessed to the ARY - return { + Next:next, - Isdone:isdone, + getcurrent:getcurrent A } at}
Abort iterator: Sets the callback function to the callback to return false when it jumps out of the loop
Examples of applications for iterators: When file uploads are available in many ways, avoid using conditional selection statements to choose how to upload
The solution might be:
- Each upload method is written as a function, the function returns the Upload object, and returns False if it is an incompatible upload method.
- Iterate through all the functions of the upload method as an array, until the iteration to an upload method is possible
- Upload using the object returned by this upload method function
JavaScript Design patterns and development practices-7th-Iterator mode