SoFunction
Updated on 2025-04-03

Deep understanding of JavaScript series (35): Detailed explanation of the iterator mode of design pattern

introduce

Iterator mode: Provides a method to order individual elements in an aggregate object without exposing the internal representation of the object.

Several characteristics of iterators are:

1. Access the contents of an aggregate object without exposing its internal representation.
2. Provide a unified interface for traversing different collection structures, thereby supporting the same algorithm to operate on different collection structures.
3. Changing the collection structure where the iterator is located while traversing may cause problems (for example, the item is not allowed to be modified in the foreach in C#).

text

In general iteration, we need to have at least 2 methods, hasNext() and Next(), so that we can traverse all objects. Let’s first give an example:

Copy the codeThe code is as follows:

var agg = (function () {
    var index = 0,
    data = [1, 2, 3, 4, 5],
    length = ;

    return {
        next: function () {
            var element;
            if (!()) {
                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 method is the same as in C#:
Copy the codeThe code is as follows:

// The result of iteration is: 1,3,5
while (()) {
    (());
}

Of course, you can also reset the data through additional methods and then continue with other operations:
Copy the codeThe code is as follows:

// Reset
();
(()); // 1

jQuery application example

A very famous iterator in jQuery is the $.each method. Through each we can pass in an additional function and then iterate on all item items, for example:

Copy the codeThe code is as follows:

$.each(['dudu', 'dudu', 'yogurt little girl', 'that MM'], function (index, value) {
    (index + ': ' + value);
});
//or
$('li').each(function (index) {
    (index + ': ' + $(this).text());
});

Summarize

The use scenario of iterator is: the results of the set often vary in different ways. We do not want to expose its internal structure, but we also let the client code transparently access the elements. In this case, we can use the iterator mode.