2013-01-03 56 views
0

有人可以解释这个递归函数的输出吗?谢谢!这个递归函数是如何来到这个输出的?

function test(a) { 
    while (a > 0) { 
     a -= 1; 
     test(a); 
     console.log('after first invocation: ' + a); 
    } 
} 

test(3);​ 

输出:

after first invocation: 0 
after first invocation: 1 
after first invocation: 0 
after first invocation: 2 
after first invocation: 0 
after first invocation: 1 
after first invocation: 0 
+0

用文字描述很长。使用调试器和断点更快。 – VisioN

+0

这里似乎没有什么令人惊讶的东西 – antlersoft

+0

那么你想了解递归如何工作,或者是否存在与此代码有关的特定问题? – SeanLi

回答

2

那么代码没有100%你告诉他这样做!

loop 1 : 
    value of a is 3, is it bigger then 0? Yes! 
    3 - 1 = 2 (why not a-- ...) 
    call function test(2) 
    is 2 bigger the 0? Yes! 
    2 - 1 = 1 
    call function test(1) 
    is 1 bigger the 0? Yes! 
    1 - 1 = 0 
    call function test(0) 
    is 0 bigger then 0 ? NO! 
    console.log(('after first invocation: ' + 0) 

我不认为我必须为每个输出做它,但我认为你明白了吗?