为什么我的函数将一个值推送太多?
Why does my function push one value too much?
我正在尝试编写自己的斐波那契函数。它应该 return 数组中小于 num
的所有斐波那契数。我尝试使用 while
循环检查 currentPush
与 num
,但它会将一个值过多地推入 returned 数组。
我的代码有什么问题?它应该在最后一次迭代之前停止,因为 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 ]
我正在尝试编写自己的斐波那契函数。它应该 return 数组中小于 num
的所有斐波那契数。我尝试使用 while
循环检查 currentPush
与 num
,但它会将一个值过多地推入 returned 数组。
我的代码有什么问题?它应该在最后一次迭代之前停止,因为 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 ]