【问题标题】:Recursive function not ending on a return statement? [duplicate]递归函数没有以 return 语句结束? [复制]
【发布时间】:2019-01-25 02:54:30
【问题描述】:

我正在学习雄辩的 javascript,这个递归函数让我很困惑,我明白了大部分。

function findSolution(target) {
  function find(current, history) {
    if (current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5)`) ||
             find(current * 3, `(${history} * 3)`);
    }
  }
  return find(1, "1");
}

console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)

绝对让我感到困惑的部分是在当前 > 目标的情况下,如果我控制台记录当前并且它多次超出目标但随后继续递归尝试不同的组合,为什么函数没有t 返回 null 并在那里结束?

【问题讨论】:

  • 因为下面有你的||
  • 因为根据else部分有两条路径可以搜索到。如果第一个解析为null,那么第二个路径仍然可以提供其他内容。
  • 顺便说一句,您可以省略 else 并继续使用简单的 if,因为 return 结束了函数。如果未返回,则继续执行,单个 if 就足够了。
  • 看这仍然是让我感到困惑的部分我知道如果运算符的左侧评估为大于目标的数字,它将转到右侧,但是如果我控制台日志我可以看到这种情况发生,然后右侧也返回一个大于目标的数字,但该语句将从一组不同的指令重新开始。

标签: javascript recursion


【解决方案1】:

因为这个:

return find(current + 5, `(${history} + 5)`) ||
            find(current * 3, `(${history} * 3)`);

当OR左边部分调用的函数返回null时,计算结果为false,所以第二部分被计算,再次调用函数

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2018-04-05
    • 1970-01-01
    • 2018-03-03
    • 2017-12-20
    • 2020-04-14
    • 2019-03-09
    • 2018-11-20
    • 2014-06-25
    相关资源
    最近更新 更多