这个递归函数是如何得到这个输出的

How does this recursive function come to this output?

本文关键字:输出 递归函数 何得      更新时间:2023-09-26

有人能解释一下这个递归函数的输出吗?谢谢你!

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

代码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)

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