JavaScript Design patterns and development practices reading notes (7)--iterator mode

Source: Internet
Author: User
Tags object object javascript array

iterator pattern : refers to providing a way to sequentially access individual elements in an aggregated object without exposing an internal representation of the Object.

The iterator pattern separates the iterative process from the business logic, and after using the iterator pattern, you can access each of these elements sequentially, even if you do not care about the internal construction of the Object.

Popular languages such as java, Ruby and so on have built-in iterator implementations, and many browsers support JavaScript Array.prototype.forEach.

iterators in jquery
1 function (i, N) {2 console.log (' the current subscript is: ' + i); 3 console.log (' current value: ' + n '); 4 });
implement your own iterators
1 vareach =function(ary, Callback) {2      for(vari = 0, L = ary.length; I < l; i++ ){3Callback.call (ary[i], i, ary[i]);//pass subscripts and elements as parameters to the callback function4 }5 };6 7Each ([1, 2, 3],function(i, N) {8 Alert ([i, n]);9});
internal iterators and external iterators

• Internal Iterators
The each function that we have just written belongs to an internal iterator, and the iteration rules are defined internally for each function, which takes over the entire iterative process and requires only one initial call from the Outside.
An internal iterator is very handy when it is called, and the outside world does not care about the implementation inside the iterator, but since the iteration rules of the internal iterator have been specified in advance, each of the above functions cannot iterate over 2 arrays at the same time.

This is true if you want to compare two arrays if they are identical without changing the function of Each.

1 varCompare =function(ary1, Ary2) {2     if(ary1.length!==Ary2.length) {3         Throw NewError (' ary1 and Ary2 not equal ' );4     }5Each (ary1,function(i, N) {6         if(n!==ary2[i]) {7             Throw NewError (' ary1 and Ary2 not equal ' );8         }9     });TenAlert (' ary1 and Ary2 equal ' ); one }; a  -Compare ([1, 2, 3], [1, 2, 4]);//throw new Error (' ary1 and Ary2 not equal '); 

· External iterators

An external iterator must explicitly request an iteration of the next element, and an external iterator increases the complexity of some calls, but we can also manually control the process or order of the Iterations.

1 varIterator =function(obj) {2     varCurrent = 0;//refers to the current serial number3     varNext =function(){//Next method, ordinal +14Current + = 1;5 };6     varIsDone =function(){//Isdone method to determine if an array traversal is complete7       returnCurrent >=obj.length;8 };9     varGetcurritem =function(){//Getcurritem method to get the specific value of the current ordinalTen       returnobj[current]; one }; a     return{//returns an object that holds the current value with a closure - next:next, - isdone:isdone, the Getcurritem:getcurritem - } - }; -  + variterator_1 = iterator ([1, 2, 3]);//Build Instance - variterator_2 = iterator ([1, 2, 3 ] ); +  a varCompare =function(iterator1, Iterator2) { at      while(!iterator1.isdone () &&!iterator2.isdone ()) {//when both are not traversed at the end -       if(iterator1.getcurritem ()!== Iterator2.getcurritem ()) {//if the value of the current ordinal is not equal -         Throw NewError (' Iterator1 and Iterator2 not equal ' ); - } -Iterator1.next ();//Serial Number Increase - Iterator2.next (); in } -Alert (iterator1+ ' and ' +iterator2+ ' equal ' ); to } +  -Compare (iterator_1, iterator_2);//output: iterator_1 and iterator_2 equal
Iterate class array objects and literal objects

Whether an internal iterator or an external iterator, as long as the aggregated object being iterated has the length attribute and can be accessed with subscript, it can be iterated.
In javascript, the for-in statement can be used to iterate over the properties of an ordinary literal object. The $.each function in jquery is as follows

1$.each =function(obj, Callback) {2     varvalue,3i = 0,4Length =obj.length,5IsArray =isarraylike (obj);6     if(isarray) {//iterating over an array of classes7        for(; I < length; i++ ) {8Value =callback.call (obj[i], i, obj[i]);9         if(value = = =false ) {Ten            break; one } a } -}Else { -        for(iinchObj) {//Iterate Object Object theValue =callback.call (obj[i], i, obj[i]); -         if(value = = =false ) { -           break; - } + } - } +     returnobj; a};
Reverse Iterator

When You're walking, you can do it back.

Abort iterator

Give a condition for the iterator to Terminate.
In each of the jquery functions, there is this sentence:

1 if false ) {2break     ; 3 }

The meaning of this code is that the contract terminates the loop prematurely if the result of the callback function returns FALSE.

Summary

The iterator pattern is a relatively simple pattern that we don't think is a design pattern in many Cases. Most of the current languages have iterators built into Them.

JavaScript Design patterns and development practices reading notes (7)--iterator mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.