问题
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