js算法之生成器构造无穷斐波那契数例

代码如下:

function* fibonacci() {
    let a =1,b =1
    yield a;yield b
    while(true) {
        const t = b
        b = a + b; a = t
        yield b
    }
}
const it = fibonacci()
// // 利用斐波那数列获得10项,也可以获得多项,这里是利用Array.from()的这个属性进行迭代器的遍历
const feb10 = Array.from(Array(10),it.next,it).map(x=>x.value)
console.log(feb10) // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]

猜你喜欢

转载自www.cnblogs.com/fanzhanxiang/p/10305957.html