Open zhenguilin opened 7 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}
generator跟函数很像,定义如下