Skip to content

迭代器模式 #16

Description

@archerU

迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露改对象的内部表示。

内部迭代器

内部迭代器的迭代规则被提前规定,外部只需要一次初始调用。

const each = function(array, callback) {
    for (let i=0,length=array.length;i<length;i++) {
    callback.call(array[i],i,array[i]); // 把下标和元素当作参数传给 callback 函数
    }
};
each([1,2,3],function(i,n) {
    console.log("i,n",[i,n]);
});

外部迭代器

外部迭代器必须显式地请求迭代下一个元素。

const Iterator = function(obj) {
    let current = 0;
    const next = function() {
        current += 1;
    };
    const isDone = function() {
        return current >= obj.length;
    };
    const getCurrentItem = function() {
        return obj[current];
    };
    return {
        next,
        isDone,
        getCurrentItem
    }
};
const iterator1 = Iterator([1,2,3]);
iterator1.getCurrentItem(); // 1
iterator1.isDone(); // false
iterator1.next(); 
iterator1.getCurrentItem(); // 2
iterator1.isDone(); // false
iterator1.next(); 
iterator1.getCurrentItem(); // 3
iterator1.isDone(); // false
iterator1.next();
iterator1.getCurrentItem(); // undefined
iterator1.isDone(); // true

倒序迭代器

迭代器模式提供了循环访问一个聚合对象中每个元素的方法,但它没有规定我们以顺序、倒序还是中序来循环遍历聚合对象。

const reverseEach = function(array, callback) {
    for(let i=array.length;i>=0;i--) {
        callback(i,array[i]);
    };
};
reverseEach([0,1,2],function(i,n) {
    console.log(n); // 2,1,0
});

中止迭代器

迭代器可以像普通 for 循环中的 break 一样,提供一种跳出循环的方法。

const each = function(array, callback) {
    for(let i=0,length=array.length;i<length;i++) {
        if (callback(i,array[i]) === false ) { // callback 的执行结果返回false,提前终止迭代
            break;
        }
    }
};

each([1,2,3,4,5],function(i,n){
    if (n>3) { // n 大于 3 的时候终止循环
        return false;
    }
    console.log(n); // 分别输出:1,2,3
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions