我正在學習遞歸以及堆棧如何工作。我無法理解此函數中的堆棧跟蹤,以及爲什麼我的console.log語句說明它們的功能;瞭解遞歸函數中的堆棧跟蹤
function expoRecursion(base, exp) {
debugger;
if(exp == 1) {
console.log('the exp value is ' + exp + ' , base is returned');
return base;
} else {
console.log('line 278 the function evaluates ' + expoRecursion(base, exp -1));
return base * expoRecursion(base, exp-1);
}
}
expoRecursion(2,3);
我已經在Chrome瀏覽器開發工具來運行這一點,並通過它加強,但似乎無法得到的,爲什麼當exp爲1返回基本情況後的性質,我們彈出expoRecursion(2,2 -1),然後進入expoRecursion(2,3-1),然後再添加到堆棧expoRecursion(2,2-1),當它已經被評估了?隨後的混亂似乎是來自他們看了我的日誌語句:
the exp value is 1 , base is returned
line 278 the function evaluates 2
the exp value is 1 , base is returned
line 278 the function evaluates 4
the exp value is 1 , base is returned
line 278 the function evaluates 2
the exp value is 1 , base is returned
爲什麼是最後一條語句2,然後最終返回值回來爲8?
你正在通過調用'expoRecursion'函數來記錄它的結果來創建新的遞歸'console.log('expoRecursion(base,exp -1));' – Titus
你的日誌語句和你的return語句都是調用遞歸。這可能不是你想要的。 – pvg
哦廢話,我沒有意識到我在console.log語句中調用函數agin。 –