代码之家  ›  专栏  ›  技术社区  ›  Munerz

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

  •  0
  • Munerz  · 技术社区  · 7 年前

    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&end?

    1 回复  |  直到 7 年前
        1
  •  1
  •   nsndvd    7 年前

    因此:

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