Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 这个递归函数是如何得到这个输出的?_Javascript_Function_Recursion - Fatal编程技术网

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

Javascript 这个递归函数是如何得到这个输出的?,javascript,function,recursion,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

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

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)

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

用文字描述很长时间。使用调试器和断点会更快。这里似乎没有什么令人惊讶的地方,所以您是在尝试学习递归是如何工作的,还是这段代码有一个特定的问题?我相信这会被认为是“深度优先”。