• js迭代器模式


    // 迭代器模式
    /**
     * 1 通常有一个包含某种数据集合的对象
     * 2 该数据集合能够提供一个简单的方法,能够访问数据中的每一项
     */
    // es5 实现
    let Arrdata = (function () {
        let index = 0; // 保存当前的下标
        let data = [1,2,3,4,5]// 复杂的数据集合
        let length = data.length; // 保存长度
        return {
            // 访问下一个元素
            next() {
                let ele;
                if(!this.hasNext()) return null;
                ele = data[index];
                index++;
                return ele;
            },
            hasNext() { // 是否有下一个
                return index < length;
            },
            rewind() { // 重置指针
                indx = 0;
            },
            current() { // 获取当前值
                return data[index];
            }
        }

    })();
    // 检验迭代器
    while(Arrdata.hasNext()) {
        console.log(Arrdata.next()); // 1,2,3,4,5
    }
    console.log(Arrdata.next()); // null


    // es6 中generator函数实现
    let a = function *() {
        let index = 0;// 保存当前的下标
        let data = [1,2,3,4,5];// 复杂的数据集合,例子中用一个简单的数组表示
        let length = data.length;// 保存长度
        while(index < length) {
            yield data[index];
            index++;
        }
        return null;

    };
    let b = a();
    console.log(b.next().value); //1
    console.log(b.next().value); //2
    console.log(b.next().value);//3
    console.log(b.next().value);//4
    console.log(b.next().value);//5
    console.log(b.next().value);//null
  • 相关阅读:
    用c和c++的方式实现栈
    类的static成员并用其实现一个单例模式
    windows安装mongodb
    centos 安装beanstalkd
    使用 OAuth2-Server-php 在 Yii 框架上搭建 OAuth2 Server
    Git Windows客户端保存用户名与密码
    PHP 输入流 php://input
    yii accessRules用法
    php curl
    yii 初步安装
  • 原文地址:https://www.cnblogs.com/windcat/p/12740378.html
Copyright © 2020-2023  润新知