问题
In the code below I understand exactly how it works, right up until the termination and the 'return 1'. I would assume that once the function terminates it should output 1 but instead it does what you would expect an exponential program to do, it outputs the correct answer which in this case is 9.
My question is why is this so ?
I assume the way I visualize recursion is incorrect ( maybe my idea of how the stack treats recursion ?) I found a similar question to mine here but it doesn't help this one granular little inking of my understanding.
function power(base,exponent){
if(exponent === 0){
return 1 // Terminates with return 1 but output is correct
}
return base * power(base, exponent-=1);
}
power(3,2) // This outputs 9 not 1. Why?
回答1:
The recursive function works like this:
At first, The function will return 3 * power(3, 1).
Now you are only invoking the function at the right hand side, so only that value must resolve so it will become.
3 * 3 * power(3,0)
Again only the right most part is a function which must resolve.
So it will be:
3*3*1
No more function is there to resole, so the first function provides you the result as 9.
it's similar to
var x = multiple(3,1) * multiple(3,2) * multiple (3,4);
Now all those functions will execute from left to right.
So once all functions are resoled, the value of x will be calculated.
回答2:
For a recursive algorithm there must be at least one base case; the recursion will eventually reach the base case. Your base case is 1, then base * power(base, exponent-1) recurses until it hits the base case, at which point it will leave you with return base * 1, which is base, then the stack will unravel, until it returns the result.
To visualize the recursion for power(3, 3) you can write the process going down first:
3 * power(3, 2)
3 * power(3, 1)
3 * power(3, 0)
Now go up and replace the recursive calls starting at the base case (last line).
3 * power(3, 2)
3 * power(3, 1)
3 * power(3, 0) = 3 * 1 = 3
// we know power(3, 0) = 1; this is the base case
Now carry up the results to do the same for the rest, until you get the final value:
3 * power(3, 2) = 3 * 9 = 27
3 * power(3, 1) = 3 * 3 = 9
3 * power(3, 0) = 3 * 1 = 3
来源:https://stackoverflow.com/questions/29509652/how-does-eloquent-javascript-recursion-example-terminate-as-return-1-but-still-o