美文网首页
初见Generator

初见Generator

作者: fighterboy | 来源:发表于2017-05-24 16:55 被阅读0次

对比两次代码

function fib(max) {

var

t,

a = 0,

b = 1,

arr = [0, 1];

while (arr.length < max) {

t = a + b;

a = b;

b = t;

arr.push(t);

}

return arr;

}

// 测试:

console.log(fib(5)); // [0, 1, 1, 2, 3]

console.log(fib(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Generator 代码

function* fibs() {

let a = 0;

let b = 1;

while (true) {

yield a;

[a, b] = [b, a + b];

}

}

let [first, second, third, fourth, fifth, sixth,seventh] = fibs();

console.log(seventh);

相关文章

网友评论

      本文标题:初见Generator

      本文链接:https://www.haomeiwen.com/subject/tqsoxxtx.html