问题
function findSolution(target) {
function find(current, history) {
if (current == target)
{debugger;
return history;
}
else if (current > target){
debugger;
return null;
}
else{
debugger;
return find(current + 5, "(" + history + " + 5)") ||
find(current * 3, "(" + history + " * 3)");
}
}
debugger;
return find(1, "1");
}
console.log(findSolution(13));
During it's working after it reaches find(33, "(((1 + 5) + 5) * 3)") why does this remove +5 from earlier and not *3 it just called?
The working of the code:
find(1, "1")
find(6, "(1 + 5)")
find(11, "((1 + 5) + 5)")
find(16, "(((1 + 5) + 5) + 5)")
too big
find(33, "(((1 + 5) + 5) * 3)") //why does this remove +5 from earlier and not *3 it just called
too big
find(18, "((1 + 5) * 3)")
too big
find(3, "(1 * 3)")
find(8, "((1 * 3) + 5)")
find(13, "(((1 * 3) + 5) + 5)")
found!
回答1:
Every invocation of find()
results in a new local history
. Your recursive calls do not change history
; they make new strings.
Thus in
return find(current + 5, "(" + history + " + 5)") ||
find(current * 3, "(" + history + " * 3)");
the function is called with the + 5
form first, and if that returns null
then it's called with the * 3
form. So the + 5
is never "removed"; that string is simply discarded.
Also, as to the ||
, if the left-hand expression returns non-null, then the right-hand side is not evaluated at all.
来源:https://stackoverflow.com/questions/46747030/how-does-recursion-function-handle-the-operator