javascript设计模式学习之七——迭代器模式

一、迭代器模式定义

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

在当前大部分语言中,都已经内置了迭代器模式。迭代器有内部迭代器和外部迭代器之分,一般现有语言中实现的大多是内部迭代器。

二、jquery中的each实现

对于数组采用数字下标访问,防止原型链上其他非数值属性的干扰。

    //类似jquery中的each迭代器
    $.each=function(obj,callback){
        var value,
        i=0,
        isArray=isArrayLike(obj),
        length=obj.length;
        if(isArray){
            for(i=0,i<length;i++){
                value=callback.call(obj,i,obj[i]);
                if(value==false){
                    break;
                }
            }
        }else{
            for(i in obj){
                value=callback.call(obj,i,obj[i]);
                if(value==false){
                    break;
                }
            }
        }
        return obj;
    };
    

三、一个外部迭代器实现

    var Iterator=function(obj){
        var current=0;
        var next=function(){
            current+=1;
        };
        var isDone=function(){
            return current>=obj.length;
        };
        var getCurrentItem=function(){
            return obj[current];
        };
        return{
            next:next,
            isDone:isDone,
            getCurrentItem:getCurrentItem
        };
    };
原文地址:https://www.cnblogs.com/bobodeboke/p/5641875.html