Getting return undefined on recursive function javascript

前端 未结 4 885
温柔的废话
温柔的废话 2021-01-26 01:58

I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i trie

4条回答
  •  忘掉有多难
    2021-01-26 02:37

    The comment by vaultah is correct:

    var i=1;
    function rec(){
        i++;
        console.log(i);
        if(i > 100){
            return i;
        }else{
            return rec();
        }
    }
    
    snippet.log(rec());
    
    


    Let's take an example that only counts to > 5 and add some output so you can see what happens more easily (but again, stepping through the code with a debugger is the right way to see how this works):

    var indent = "";
    var i=1;
    function rec(){
        var rv;
        i++;
        indent += " ";
        if(i > 5){
          snippet.logHTML("

    " + indent + i + " > 5, returning " + i + "

    "); rv = i; }else{ snippet.logHTML("

    " + indent + i + " is not > 5, calling rec

    "); rv = rec(); snippet.logHTML("

    " + indent + "Got " + rv + " back from rec, returning it

    "); } indent = indent.substring(0, indent.length - 6); return rv; } snippet.logHTML("

    Final result: " + rec() + "

    ");
    
    


提交回复
热议问题