JavaScript Design patterns and development practices-7th-Iterator mode

Source: Internet
Author: User

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

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.