代码少,性能差的递归实现
function fibonacci(n) {if (typeof n !== "number" || n % 1 !== 0) return;
if (n === 0 || n === 1) {return 1;}
return fibonacci(--n) + fibonacci(n);
}
代码多,性能绝对较好的循环实现
function fibonacci(n) {if (typeof n !== "number" || n % 1 !== 0) return;
if (n === 0 || n === 1) {return 1;}
let preValue = 1;
let curValue = 1;
for (let i = 2; i <= n; i++) {[preValue, curValue] = [curValue, preValue + curValue];
}
return curValue;
}