[英]Javascript recursive function not return the result
this maybe is not the biggest challenging problem but I've got curious about it.这也许不是最大的挑战,但我很好奇。 I did a simple code just to get the Fibonacci value based on the user input without recursion and works just fine.
我做了一个简单的代码,只是为了根据用户输入获得斐波那契值,没有递归并且工作得很好。 Very simple code:
非常简单的代码:
function fib(n) {
let fibArray = [0,1];
let count = 0;
while(fibArray.length <= n){
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
return fibArray[n];
}
But the moment I tried to make it as a recursive function, the result is undefined, even if the value is not.但是当我试图将其作为递归 function 时,结果是未定义的,即使值不是。
function fib(n, count = 0, fibArray = [0,1]){
if(fibArray.length - 1 === n){
return fibArray[n];
}
if (fibArray.length <= n ) {
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
fib(n,count, fibArray);
}
Just add a return
statement in the last line.只需在最后一行添加一个
return
语句。
return fib(n,count, fibArray);
The code is ok, you just need to add a return:代码没问题,你只需要添加一个返回:
function fib(n, count = 0, fibArray = [0,1]){
if(fibArray.length - 1 === n){
return fibArray[n];
}
if (fibArray.length <= n ) {
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
return fib(n,count, fibArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.