递归函数不以返回语句结尾? [英] Recursive function not ending on a return statement?

查看:75
本文介绍了递归函数不以返回语句结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习雄辩的 javascript &这个递归函数把我难住了,大部分我都懂.

I'm going through eloquent javascript & this recursive function has me stumped, I understand most of it.

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 &到此为止?

The part that absolutely baffles me is in the case when the current > target, if I console log the current and it exceeds the target numerous times but then continues with the recursion trying a different combination, why is it the function doesn't return null & end there?

推荐答案

因此:

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

当 OR 左边部分调用的函数返回 null 时,它的计算结果为 false,因此计算第二部分,并再次调用该函数

When the function called at the left part of the OR returns a null, it evaluates to false, so the second part is evaluated, and the function is called again

这篇关于递归函数不以返回语句结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆