創(chuàng)建數(shù)組
function fbnq1(No) {
let arr = [1, 1];
if (No <= 2) return 1;
// 第5個(gè)數(shù) 算出 下標(biāo)為4的數(shù) 數(shù)組長(zhǎng)度為5
while (arr.length < No) {
// 獲取第幾項(xiàng)那就計(jì)算最后一項(xiàng)的值 直到數(shù)組有幾項(xiàng)
// 計(jì)算倒數(shù)第一項(xiàng)和倒數(shù)第二項(xiàng)的和 產(chǎn)生新的值
arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
}
//返回計(jì)算好的最后一項(xiàng)
return arr;
// return arr[arr.length - 1];
}
console.log(fbnq(1)); // 1
console.log(fbnq(2)); // 1
console.log(fbnq(3)); // 2
console.log(fbnq(4)); // 3
console.log(fbnq(5)); // 5
console.log(fbnq(6)); // 8
console.log(fbnq(7)); // 13
console.log(fbnq(8)); // 21
console.log(fbnq(9)); // 34
console.log(fbnq(10)); // 55
console.log(fbnq(11)); // 89
遞歸方式
function fbnq(No) {
if (No <= 2) return 1;
// 第一個(gè)數(shù),第二個(gè)數(shù) 玉雾, 當(dāng)前是第幾個(gè)數(shù)字
function fn(last1, last2, curNo) {
if (curNo >= No) {
return last2;
} else {
// 原來的第二個(gè)數(shù)作為第一個(gè)數(shù)
// 加和的最新數(shù)作為第二個(gè)數(shù)
// 遞歸計(jì)算下一個(gè)數(shù) + 1
return fn(last2, last1 + last2, curNo + 1);
}
}
return fn(1, 1, 2);
}