简体   繁体   English

了解递归函数如何在javascript中工作

[英]Understanding how a recursive function works in javascript

I am a little bit confused on the exact execution timeline in which the following function runs. 我对运行以下函数的确切执行时间表有些困惑。 I saw this code on the MDN guide: 我在MDN指南上看到了以下代码:

function foo (i)  {
    if (i<0) return;
    console.log('begin' + i);
    foo(i-1);
    console.log('end' + i);
} 

Based on my knowledge of how functions work, this is what I thought, though my knowledge is inadequate: 根据我对功能如何工作的了解,这是我的想法,尽管我的知识不足:

I think when the function foo(3) is called, it will go to the function and check the condition if i < 0 , then it will run the next code console.log('begin:' + i) . 我认为当调用函数foo(3) ,它将转到该函数并检查条件if i < 0 ,然后它将运行下一个代码console.log('begin:' + i)

After that, the next line of code is executed, since JavaScript execute line by line, the next line of code which is foo(i-1) will be executed. 之后,将执行下一行代码,由于JavaScript逐行执行,因此将执行下一行代码foo(i-1)

It takes the current value of i which is 3 minus 1, so foo(2) is called and the execution continues. 它采用i的当前值3减1,因此将调用foo(2)并继续执行。


My question is: Is my understanding correct? 我的问题是: 我的理解正确吗? . If no please explain what this code is doing, otherwise can anyone explain breiefly when will the function stop being called? 如果否,请解释该代码的作用,否则有人可以简短地解释何时停止调用该函数?

What happens when you call foo(3) is as follows (in pseudocode): 调用foo(3)时,将发生以下情况(使用伪代码):

execute foo(3)
    3 is greater than 0 thus log(begin 3)
    execute foo(2)
        2 is greater than 0 thus log(begin 2)
        execute foo(1)
            1 is greater than 0 thus log(begin 1)
            execute foo(0)
                0 is equal to 0 thus log(begin 0)
                execute foo(-1)
                    -1 is less than 0 thus return
                log(end 0)
            log(end 1)
        log(end 2)
    log(end 3)
return

It works like this: 它是这样的:

foo(3)->

if (3 < 0)
  return
console.log('begin' + 3)
if (2 < 0)
  return
console.log('begin' + 2)
if (1 < 0)
  return
console.log('begin' + 1)
if (0 < 0)
  return
console.log('begin' + 0)
if (-1 < 0)
  return
console.log('end' + 0)
console.log('end' + 1)
console.log('end' + 2)
console.log('end' + 3)

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

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