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)
我不认为我必须对每一个输出都这样做,但我想你明白了吗?用文字描述很长时间。使用调试器和断点会更快。这里似乎没有什么令人惊讶的地方,所以您是在尝试学习递归是如何工作的,还是这段代码有一个特定的问题?我相信这会被认为是“深度优先”。