Look at this recursive method, the last output value
function fn (i) { I++ ; if (i<10) { fn (i); } Else { return i; }} var result = fn (0); Console.log (result);
Most people may say the result is 10, but the real result is undefined. Why is it? Because for each function, the return value of return is not written, in fact, for var a = function (); is not to assign a value, then this value is the default undefined value, you can typeof a test, the return value is ' undefined '. So it can be said that the default is a return value of return undefined; so we're going to deform this recursively. As follows:
function fn (i) { I++ ; if (i<10) { fn (i); } Else { return i; } return undefined;} var result = fn (0); Console.log (result);
Of course, the result is the same as the result above. What is the specific principle? What is it for? If you see this if else and recursion, you think of the binary tree's first order traversal. Specifically looking at the code.
function fn (i) { I++ ; if (i<10) { Console.log ("A:" +i); FN (i); } Else { Console.log ("C:" +i); return i; } Console.log ("d:undefined" +i); return undefined;} var result = fn (0); Console.log (result);
Output Result:
Look at the view of the two-fork tree:
From the results of the output and the two-tree view can clearly see the principle of recursive traps, it is very simple, for this recursion can see the wrong binary tree of the first order traversal. When the right node is traversed, there is no direct return value, so the default is undefined. When the last traversal is made to the initial node, a undefined is returned.
So this should understand the principle of recursion of this trap problem. Of course, this trap is avoided as long as we use the return value in each condition. The specific code is as follows:
function fn (i) { I++ ; if (i<10) { return fn (i); } Else { return i; }} var result = fn (0); Console.log (result);
The trap problem of function function recursion in JavaScript