【问题标题】:Understanding the stack trace in recursive function了解递归函数中的堆栈跟踪
【发布时间】: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


【解决方案1】:

其他人已经指出了你混淆的原因:你在 else 子句中重复了 两次。我认为这将为您清理它:只重复一次,保存结果,并在两个地方都使用 that

} else {
    recur_result = expoRecursion(base, exp -1);
    console.log('line 278 the function evaluates ' + recur_result);
    return base * recur_result;
}

看看这是否符合您的期望。

【讨论】:

  • 明白,我看到了我的错误,以及是什么让我更加困惑。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2017-11-27
  • 2020-07-06
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
相关资源
最近更新 更多