【发布时间】:2017-04-06 15:23:37
【问题描述】:
我正在学习递归以及堆栈的工作原理。我无法理解此函数中的堆栈跟踪以及为什么我的 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)); -
您的日志语句和您的返回语句都调用递归。这可能不是你想要的。
-
哦,废话,我没有意识到我在 console.log 语句中调用了函数 agin。
标签: javascript recursion computer-science