Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

迭代器模式 #16

Open
archerU opened this issue Jun 5, 2018 · 0 comments
Open

迭代器模式 #16

archerU opened this issue Jun 5, 2018 · 0 comments

Comments

@archerU
Copy link
Owner

archerU commented Jun 5, 2018

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

内部迭代器

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

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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant