我正在尝试编写自己的斐波那契函数。它应该返回数组中所有小于 num
的斐波那契数。我尝试使用 while
循环检查 currentPush
与 num
,但它会将一个值过多地插入返回的数组。
我的代码有什么问题吗?它应该在最后一次迭代之前停止,因为 currentPush
肯定大于 num
。
function fib(num) {
if(num < 2){return 1};
let fib = [1, 1];
let currentPush = 2;
while (currentPush < num){
// get last two elements from array and add them together
currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
fib.push(currentPush);
}
return fib;
}
console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]
最佳答案
正如评论中提到的,您必须检查 currentPush < num
在插入数组之前但在计算之后 currentPush
function fib(num) {
if(num < 2) {return 1};
let fib = [1, 1];
while (true) {
let currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
if (currentPush > num)
return fib;
fib.push(currentPush);
}
}
console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]
关于javascript - 为什么我的函数将一个值推得太大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398947/