这个递归函数如何产生这个输出?

时间:2013-01-03 23:05:10

标签: javascript function recursion

有人可以解释这个递归函数的输出吗?谢谢!

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

1 个答案:

答案 0 :(得分:2)

代码完全按照你的要求做了!

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)

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