![](/img/trans.png)
[英]How to save the return value of a recursive function in a variable JavaScript
[英]How is my variable changing value during the return statement in a recursive algorithm?
我正在使用 Javascript 中的鏈表進行練習。 作為我的解決方案的一部分,我有一個 function,它采用一個數字整數的鏈表並將其轉換為單個數字。 返回的值與返回前一行記錄到控制台的值不同。
例如,如果我輸入(2 -> 4 -> 3)
,我的 console.log 應該是342
,但在otherFunction
中返回的值是386
。 輸入(5 -> 6 -> 4)
記錄465
,但返回535
。
num
的值如何變化?
function parseListNumber(list, num = 0, multiplier = 1) {
digitValue = list.val * multiplier;
multiplier *= 10;
num += digitValue;
if (list.next) {
return num + parseListNumber(list.next, num, multiplier);
} else {
console.log(num) // num is correct here
return num;
}
}
function otherFunction(list) {
parseListNumber(list); // returned value is now somehow larger
};
每次輸入if
語句時,都會將num
添加到遞歸調用中。 如果你刪除它,那么當你達到你的基本情況時,你的值將通過以前的遞歸調用進行備份並保持不變。
請參見下面的示例:
const list = { val: 2, next: { val: 4, next: { val: 3 } } }; function parseListNumber(list, num = 0, multiplier = 1) { let digitValue = list.val * multiplier; multiplier *= 10; num += digitValue; if (list.next) { return parseListNumber(list.next, num, multiplier); // remove `num +` (use tail recursion) } else { console.log(num) // num is correct here return num; } } function otherFunction(list) { console.log("Actual res: ", parseListNumber(list)); }; otherFunction(list);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.