菲契那波数列1,1,2,3,5,8,13,21,34,55,89,有如下函数F(0) = 1 F(1) = 1 F(2) = 2,
请写出Fn函数,要求:输出参数从0开始,输出对
此题主要考察Generator 函数的用法和基本的数据结构
如果不了解Generator参考 阮一峰ES6
function* ficinabo(max) {
var initNum = 1,
nextValue = 1,
i = 0
while(i <= max) {
yield initNum;
[initNum, nextValue] = [nextValue, initNum + nextValue]
i ++
}
return
}
function imMet(v){
let arr = []
for(var x of ficinabo(v)){
arr.push(x)
}
if(arr.length > 0){
return arr.pop()
}
}
测试:
第二种:
function fibonacci(n) {
/*
*斐波那契数列前两项都是1,所以判断n是否等于1或者2,如果是则直接返回1
*/
n = n && parseInt(n);
if (n == 1 || n == 2) {
return 1;
};
// 使用arguments.callee实现递归
return arguments.callee(n - 2) + arguments.callee(n - 1);
}
let sum = fibonacci(8)
console.log(sum) // 21
第三种:
function fibonacci(n) {
n = n && parseInt(n);
let n1 = 1;
let n2 = 1;
// n 等于 1 或 n 等于 2 的时候直接返回1
if(n == 1 || n == 2) {
return 1;
}
// 使用解构赋值,n1 等于 n2,n2 等于 n1 + n2 最后返回 n2
for (let i = 2; i < n; i++) {
[n1, n2] = [n2, n1 + n2]
}
return n2
}