• 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
            };
        };
  • 相关阅读:
    操作系统进程调度策略
    runnable & callable
    leetcode 124 二叉树中的最大路径和
    leetcode 24 两两交换链表中的节点
    leetcode 93 复原IP地址
    C++ 11 move
    leetcode 64 最小路径和
    leetcode 1143 最长公共子序列
    leetcode 528 按权重随机选择
    数据挖掘面试题(1)
  • 原文地址:https://www.cnblogs.com/bobodeboke/p/5641875.html
Copyright © 2020-2023  润新知