简体   繁体   中英

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 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 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);
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM