频道栏目
首页 > 程序开发 > web前端 > JavaScript > 正文
js设计模式之BehavioralPatterns之Iterator
2018-06-07 14:34:04      个评论    来源:qq_37414243的博客  
收藏   我要投稿
class KingSuccession {
    constructor(inLineForThrone){
        this.inLineForThrone = inLineForThrone;
        this.pointer = 0;
    }
    next(){
        return this.inLineForThrone[this.pointer++];
    }
}
var kin = new KingSuccession(["Robert Baratheon","JofferyBaratheon","TommenBaratheon"]);
kin.next();
kin.next();
kin.next();

An interesting application of iterators is to not iterate over a fixed collection. For
instance an iterator can be used to generate sequential members of an infinite set
like the fibonacci sequence:

class FibonacciIterator{
    constructor(){
        this.previous = 1;
        this.beforePrevious = 1;
    }
    next(){
        var current = this.previous + this.beforePrevious;
        this.beforePrevious = this.previous;
        this.previous = current;
        return current;
    }
}
var fib = new FibonacciIterator();
fib.next();
fib.next();
fib.next();

Iterators are a syntactic nicety that has long been missing from JavaScript. Another
great feature of ECMAScript-2015 are generators. This is, in effect, a built in iterator
factory. Our fibonacci sequence could be rewritten like the following:

function* FibonacciGenerator () {
    var previous = 1;
    var beforePrevious = 1;
    while (true){
        var current = previous + beforePrevious;
        beforePrevious = previous;
        previous = current;
        yield  current;
    }
}
var fibo = new FibonacciGenerator();
fibo.next().value;
fibo.next().value;
fibo.next().value;
点击复制链接 与好友分享!回本站首页
上一篇:js获取当天00:00:00到23:59:59的时间并格式化
下一篇:JSON语法之JSON键/值对
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站