js迭代器模式

在迭代器模式中,通常有一个包含某种数据的集合的对象。该数据可能储存在一个复杂数据结构内部,而要提供一种简单

的方法能够访问数据结构中的每个元素。

实现如下:

//迭代器模式
var agg = (function(){
    var index = 0,
        data = [1,2,3,4,5],
        length = data.length;
    return{
        next:function(){
            var element;
            if(!this.hasNext()){
                return null;
            }
            element = data[index];
            index += 2;
            return element;
        },
        hasNext:function(){
            return index < length;
        },
        //重置指针回到初始位置
        rewind:function(){
            index = 0;
        },
        //返回当前元素
        current:function(){
            return data[index];
        }
    };
}());
//test
while(agg.hasNext()){
    console.log(agg.next()); //1 3 5
}
//回退
agg.rewind();
console.log(agg.current());  //1
原文地址:https://www.cnblogs.com/scnuwangjie/p/5005788.html