zoukankan      html  css  js  c++  java
  • js设计模式--迭代器模式

    迭代器模式:

    迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该方法中的内部表示。js中我们经常会封装一个each函数用来实现迭代器。

    理解的意思:提供一个方法,去把对象的每一项按照一定的方法,访问各个元素。

    上代码:

    var agg = ((function(){
        var index = 0,
        arr = [1,2,3,4,5,6],
        length = arr.length;
    
        return {
            next:function(){                     //向下进行
                var ele;
                if(!this.hasNext) return null;   //当索引值大于集合的length时判断停止
                ele = arr[index];                //获取的元素
                index = index +2;                //索引
                return ele;                        //返回查找到的元素
            },
            hasNext:function(){                 //判断是否已经找完了
                return index<length;
            },
            rewind:function(){                    //把指针归零重置
                index=0;
            },
            current:function(){                    //返回指定的数值
                return arr[index]
            }
        }
    
    })())

     执行:

    while (agg.hasNext()) {
        console.log(agg.next());  // 1,3,5
    }

     当然,你也可以通过额外的方法来重置数据,然后再继续其它操作:

    // 重置
    agg.rewind();
    console.log(agg.current()); // 1

    在jQuery这种也有这样的形式,比如each,

    $.each([1, 2, 3, 4], function (index, value) {
        console.log(index + ': ' + value);
    });

    写了个例子,操作数组:

    function each(arr,callBack){
        for(var i=0;i<arr.length;i++){
            if(callBack.call(arr[i],i,arr[i]) === false){
                          return false;
                }
        }
    
    };
    var as = [1,2,3,4,5];
    each(as,function(index,item){
        console.log(index);//0,1,2,3,4
    }); 

    写了个例子,操作对象:

    function each(arr,callBack){

      for(var i in arr ){
        if(callBack.call(arr[i],i,arr[i]) === false){
          return false;
        }
      }

    }


    var as = {a:1,b:2,c:3,d:4};

    each(as,function(index,item){

    console.log(index);a,b,c,d

    });

    迭代器的使用场景是:对于集合内部结果常常变化各异,我们不想暴露其内部结构的话,但又响让客户代码透明底访问其中的元素,这种情况下我们可以使用迭代器模式。

    参考:《javascript设计模式》

    汤姆大叔:http://www.cnblogs.com/TomXu/archive/2012/03/09/2358903.html

     

  • 相关阅读:
    [转]OnKeyDown Numeric Validator CLIENT SIDE
    [转]ng-grid
    死锁
    MySQL中间层 Atlas
    构建高性能web之路------mysql读写分离实战
    springboot读写分离--temp
    MySQL数据库的同步配置+MySql读写分离
    JMX学习笔记(二)-Notification
    kafka之四:Kafka集群搭建
    Synchronized之四:Synchronized的可重入性
  • 原文地址:https://www.cnblogs.com/floatboy/p/module_3.html
Copyright © 2011-2022 走看看