本文主要是介绍初见Generator,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对比两次代码
function fib(max) {vart,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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!