一个无限的斐波拉契数列 1 1 2 3 ...

138 阅读1分钟

使用迭代器输出一个无线的斐波拉契数列

    let iterator = {
        a:1,
        b:1,
        curIndex:0, //当前取到斐波拉契数列的第几位,从一开始
        next(){
            if(this.curIndex===0 || this.curIndex === 1){
                this.curIndex++;
                return {
                    value:{
                        number:1,
                        curIndex:this.curIndex
                    },
                    done:false
                };
                
            }
            let c=this.a + this.b;
            this.curIndex++;
            this.a = this.b;
            this.b = c;
            return {
                value:{
                    number:c,
                    curIndex:this.curIndex
                },
                done:false
            };
        }
    }