1

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

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
4

1 回答 1

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)

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

于 2013-01-03T23:16:06.427 回答