Iterator

Sequentially access the elements of a collection.

jQuery's each method is an implementation of the Iterator Pattern.



Overview


The Iterator Pattern allows traversal (or looping) over a collection of objects. Collections in JavaScript include arrays and the properties on objects. jQuery's implementation of the iterator pattern is the each method and handles both collection types as the example below demonstrates. Here is an example of where jQuery is used to iterate over an array:

var rhyme = ["Eeny", "Meeny", "Miny", "Moe"];

$.each(rhyme, function (index, value) {
    alert(index + ": " + value);    // => 0: Eeny, 1: Meeny, 2: Miny, 3: Moe
});

And here jQuery iterates over object properties:

var employee = {first: "Jonathan", last: "VanderHorn"};

$.each(employee, function (index, value) {
    alert(index + ": " + value);   // => first: Jonathan, last: VanderHorn
});

The source code of each shows that it is able to handle either type. These are the relevant lines in that method:

each: function( obj, callback, args ) {
    var name,
        i = 0,
        length = obj.length,
        isObj = length === undefined || jQuery.isFunction( obj );

    // ..

    if ( isObj ) {
        for ( name in obj ) {
            if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
                break;
            }
        }
    } else {
        for ( ; i < length; ) {
            if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
                break;
        }
    }
}

The iterator is not written from scratch with methods like: current, next, and hasNext as explained in the original GoF Iterator pattern. Instead it uses the built-in for and the for-in constructs. In the code above we can see that the if block iterates over object properties (using for-in) and the else block iterates over arrays (using for).



  Singleton
Observer