javascript递归返回错误的值

raf*_*tor 1 javascript recursion

我正在处理一个递归函数,它似乎返回了错误的值而不是预期的值.我能够复制它并将功能简化为:

function foo(i, target){    
    if(i < target){
        i++;
        foo(i, target);
    }

    return i;   
}
console.log(foo(0,5));
Run Code Online (Sandbox Code Playgroud)

基本上,鉴于上面的函数,我希望返回值为5.但是,它似乎返回1.当我做一些跟踪时,我注意到"返回i"被调用了几次,每次它都会减1 ?这种行为的原因是什么,我该怎么做才能解决这个问题?

Sur*_*yan 5

您还需要if在代码中返回表单部分.

function foo(i, target){    
    if(i < target){
        i++;
        return foo(i, target);
    }
   
    console.log(i);
    return i;   
}

console.log(foo(0,5));
Run Code Online (Sandbox Code Playgroud)

为什么你的代码返回1?

因为它只在foo每次调用时都会调用i < target它,然后按顺序从嵌套调用中返回所有值,5, 4, 3, 2, 1并打印从第一个函数调用返回的最后一个值.你可以通过在console.log之前放简单来检查这个return i并与上面的结果进行比较.

function foo(i, target){    
    if(i < target){
        i++;
        foo(i, target);
    }
   
    console.log(i);
    return i;   
}

console.log(foo(0,5));
Run Code Online (Sandbox Code Playgroud)

要可视化返回的值,您可以看到

 console.log()                               console.log()
 |   Call with 1                             -- return Call with 1
 |   |   Call with 2                            -- return Call with 2
 |   |   |   Call with 3                           -- return Call with 3
 |   |   |   |   Call with 4                          -- return Call with 4
 |   |   |   |   |   Call with 5        VS               -- return Call with 5  
 |   |   |   |   |   return 5
 |   |   |   |   return 4
 |   |   |   return 3
 |   |   return 2
 |-- return 1
Run Code Online (Sandbox Code Playgroud)