zhenguilin / javascript-note

Here are some notes for javascript
https://github.com/zhenguilin/javascript-note
0 stars 0 forks source link

generator #16

Open zhenguilin opened 6 years ago

zhenguilin commented 6 years ago

generator跟函数很像,定义如下

function* foo(x) {
    yield x + 1;
    yield x + 2;
    return x + 3;
}
zhenguilin commented 6 years ago

调用generator对象有两个方法,一是不断地调用generator对象的next()方法,第二个方法是直接用for ... of循环迭代generator对象,这种方式不需要我们自己判断done


function* fib(max) {
    var
        t,
        a = 0,
        b = 1,
        n = 1;
    while (n < max) {
        yield a;
        t = a + b;
        a = b;
        b = t;
        n ++;
    }
    return a;
}
var f = fib(5);
f.next(); // {value: 0, done: false}
f.next(); // {value: 1, done: false}
f.next(); // {value: 1, done: false}
f.next(); // {value: 2, done: false}
f.next(); // {value: 3, done: true}