JavaScript Design patterns and development Practices---reading notes (7) Iterator mode

Source: Internet
Author: User

The iterator pattern refers to providing a way to sequentially access individual elements in an aggregated object without exposing the object's internal representation.

The Array.prototype.foreach in JavaScript.

Iterators in 1.JQuery

$.each function

2. Implement each function yourself

    var function (ary,callback) {        for (var i=0,l=ary.length;i<l;i++) {            Callback.call (ary[ I],i,ary[i]); // pass subscripts and elements as parameters to the callback function         }    };    each ([n/A],function(i,n) {        alert ([I,n]);    });

3. Internal iterators and external iterators
An internal iterator is very handy when it is called, and the outside of the iterator is not concerned with the internal implementation of iterators, and the interaction with iterators is only an initial call, but this is also the disadvantage of an internal iterator. Because the iterative rules of the internal iterators have been stipulated well in advance, some requirements are not well implemented.

An external iterator must explicitly request an iteration of the next element.

External iterators increase the complexity of some calls, but they also enhance the flexibility of iterators, and we can manually control the process or order of iterations.

4. The iterator pattern can not only iterate over algebraic groups, but also iterate over the objects of some class arrays.

In JavaScript, the for-in statement can be used to iterate over the properties of an ordinary literal object.

5. Reverse Iterator

6. Abort iterator

7. Application examples

8. Summary

The iterator pattern is a relatively simple pattern that we don't think is a design pattern in many cases.

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.