Recursive function not ending on a return statement? [duplicate]

时光毁灭记忆、已成空白 提交于 2021-01-29 12:34:24

问题


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)

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?


回答1:


Because of this:

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

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



来源:https://stackoverflow.com/questions/51905973/recursive-function-not-ending-on-a-return-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!