1. define

The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object.

  1. The core

After using the iterator pattern, each element of an object can be accessed sequentially, even if the object’s internal construction is not concerned

  1. implementation

The map forEach of arrays in JS already has iterators built in

[1.2.3].forEach(function(item, index, arr) {
    console.log(item, index, arr);
});
Copy the code

But if you’re going to iterate over an object, you’re not going to be able to use the same traversal code that you would for an array and we can encapsulate that

function each(obj, cb) {
    var value;

    if (Array.isArray(obj)) {
        for (var i = 0; i < obj.length; ++i) {
            value = cb.call(obj[i], i, obj[i]);

            if (value === false) {
                break; }}}else {
    // All properties on the prototype chain are accessed when the for in loop iterates through the properties of the object:
    // It is always recommended to use the hasOwnProperty method. This will avoid the interference of the prototype object extension:
        for (var i in obj) {
            if(obj.hasOwnProperty(i) === true){
                value = cb.call(obj[i], i, obj[i]);
            }            
            if (value === false) {
                break;
            }
        }
    }
}

each([1.2.3].function(index, value) {
    console.log(index, value);
});

each({a: 1.b: 2}, function(index, value) {
    console.log(index, value);
});

/ / 0 to 1
/ / 1. 2
/ / 2, 3

// a 1
// b 2
Copy the code

Let’s look at another example of forcing an iterator to see that iterators can also replace frequent conditional statements

Although the example is not very good, it is also worth considering in the case of other responsible branch judgments

function getManager() {
    var year = new Date().getFullYear();

    if (year <= 2000) {
        console.log('A');
    } else if (year >= 2100) {
        console.log('C');
    } else {
        console.log('B');
    }
}

getManager(); // B
Copy the code

Split each conditional statement into logical functions and iterate over them in iterators

function year2000() {
    var year = new Date().getFullYear();

    if (year <= 2000) {
        console.log('A');
    }

    return false;
}

function year2100() {
    var year = new Date().getFullYear();

    if (year >= 2100) {
        console.log('C');
    }

    return false;
}

function year() {
    var year = new Date().getFullYear();

    if (year > 2000 && year < 2100) {
        console.log('B');
    }

    return false;
}

function iteratorYear() {
    for (var i = 0; i < arguments.length; ++i) {
        var ret = arguments[i]();

        if(ret ! = =false) {
            returnret; }}}var manager = iteratorYear(year2000, year2100, year); // B
Copy the code