简体   繁体   English

javascript中的递归和函数调用

[英]recursion and function call in javascript

 function test(param, n) { console.log(param, "start --- ", n); if (n > 1) { console.log(param, "before first recursion --- ", n); test("test-1", n - 1); console.log(param, "after first recursion --- ", n); test("test-2", n - 1); console.log(param, "after second recursion --- ", n); } console.log(param, "end --- ", n); } test("initialize", 3);

In output console在输出控制台中

test-1 after first recursion --- I am getting value 2 , can someone please explain the flow of code is going as, I was expecting 3 as the output, because in my understanding if the test("test-1", n-1) is completed then the next call ie test("test-2", n-1) will be getting 3 value as fresh input, also is the js working synchronous here ?第一次递归后的 test-1 ---我得到了值2 ,有人能解释一下代码的流程吗,我期待3作为输出,因为在我的理解中,如果test("test-1", n -1)完成然后下一个调用即test("test-2", n-1)将获得3 个值作为新输入,js 是否在这里同步工作?

You could use some indentations to the output and look which level is actually running.您可以对输出使用一些缩进并查看实际运行的是哪个级别。

 function test(param, n, level = 0) { console.log(''.padStart(level * 2), level, param, "start --- ", n); if (n > 1) { test("test-1", n - 1, level + 1); test("test-2", n - 1, level + 1); } console.log(''.padStart(level * 2), level, param, "end --- ", n); } test("initialize", 3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM