簡體   English   中英

javascript遞歸返回錯誤的值

[英]javascript recursion return wrong value

我正在處理一個遞歸函數,它似乎返回的值比預期的錯誤。 我能夠復制它並將功能簡化為:

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

    return i;   
}
console.log(foo(0,5));

基本上,給定上面的函數,我希望返回值是5。但是,它似乎返回1。當我進行一些跟蹤時,我注意到“ return i”被調用了幾次,每次將其遞減1 ? 出現這種現象的原因是什么,我該如何解決?

您還需要從代碼中的if部分返回。

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

為什么您的代碼返回1?

因為它僅在i < target每次都調用foo ,所以在它之后,您將獲得從嵌套調用返回的所有值的順序為5、4、3、2、1 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)); 

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

 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

您沒有返回遞歸調用的值

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

您還必須return遞歸函數調用:

return foo(i, target);

 function foo(i, target) { if (i < target) { i++; // Change here... return foo(i, target); } return i; } console.log(foo(0, 5)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM