实现斐波那契数列之es5、es6
es5实现斐波拉契函数数列:
<script type="text/javascript"> function fibonacci(n) { var one = 1; var two = 1; for(var i = 3; i <= n; i++) { //此处代码重点部分,用three累加前两个数的和,也是斐波那契数列的精髓所在。 var three = one + two; one = two; two = three; } if (n==1||n==2) { //判断n==1或2的情况下返回undefined return one; } return three; //最后返回three } console.log(fibonacci(2)); </script>
es6实现斐波拉契函数数列:
function* fibonacci() { let [prev, curr] = [0, 1]; for (;;) { yield curr; [prev, curr] = [curr, prev + curr]; } } for (let n of fibonacci()) { if (n > 1000) break; console.log(n); }
参考链接:https://www.cnblogs.com/bitkuang/p/9711304.html
http://es6.ruanyifeng.com/#docs/generator