generator(生成器)

generator和函数不同的是,generator由function*定义(注意多出的*号),并且,除了return语句,还可以用yield返回多次。

function* dawn(max) {
var
t,
a = 0,
b = 1,
n = 0;
while (n < max){
yield a;
[a, b] = [b, a + b];
n ++;
}
return
}
function* foo(x) {
yield x + 1;
yield x + 2;
return x + 3;
}
var f = dawn(5);
/*
next()方法会执行generator的代码,然后,每次遇到yield x;就返回一个对象{value: x, done: true/false},
然后“暂停”。返回的value就是yield的返回值,done表示这个generator是否已经执行结束了。如果done为true,
则value就是return的返回值。
*/
//第一种方法
console.log('第一次', f.next());
console.log('第二次', f.next())
//第二种方法
for (var x of dawn(10)) {
console.log(x); // 依次输出0, 1, 1, 2, 3, ...
}

 

posted @ 2019-03-21 15:39  yh不可说  阅读(617)  评论(0编辑  收藏  举报