/**普通函数**/
console.log("========普通函数============");
function fib(max) {
var t, a = 0,
b = 1,
arr = [1, 1];
while (arr.length < max) {
[a, b] = [b, a + b];
arr.push(b);
}
return arr;
}
console.log(fib(5));
console.log(fib(10));
console.log("========generator函数============");
/**generator函数**/
function* fib_gen(max) {
var t, a = 0,
b = 1,
n = 0;
while (n < max) {
yield a;
[a, b] = [b, a + b];
n++;
}
return;
}
//首先使用普通函数的调用方法
console.log(fib_gen(5));
//结果打印出来的是个generator对象,所以这种调用只是创建了一个gengrator对象,其实并没有去调用他
//怎么调用呢?有两种方法
//第一种是不断的调用对象自身的next方法
var f = fib_gen(5);
console.log(f.next(), "gen_fn1"); // {value: 0, done: false}
console.log(f.next(), "gen_fn1"); // {value: 1, done: false}
console.log(f.next(), "gen_fn1"); // {value: 1, done: false}
console.log(f.next(), "gen_fn1"); // {value: 2, done: false}
console.log(f.next(), "gen_fn1"); // {value: 3, done: false}
console.log(f.next(), "gen_fn1"); // {value: undefined, done: true}
// 可以看到这种方法,每次执行的时候都返回了一个对象,然后暂停,对象的value就是yeild的返回值,
// done则表示这个对象是否执行成功,当done为true的时候这个对象就执行完毕了,不会再调用next了
// 第二种方法是使用for..of方法来循环迭代generator对象,这种情况我们不用自己判断done
for (var x of fib_gen(10)) {
console.log(x, "gen_fn2")//依次输出数列
}
/**
generator函数的作用:
1. 用来保存函数的执行状态
2. 用同步的写法实现异步
**/
console