递归函数不以return语句结尾吗?

时间:2018-08-18 06:37:12

标签: javascript recursion

我正在使用精通的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)

当我>当前目标时,绝对让我感到困惑的是,如果我控制台记录当前并且多次超过目标,然后继续递归尝试不同的组合,为什么该功能不起作用?返回null并在那里结束?

1 个答案:

答案 0 :(得分:1)

因此,

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

当在OR左侧调用的函数返回null时,其结果为false,因此对第二部分进行求值,然后再次调用该函数