繁体   English   中英

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

[英]Understanding how a recursive function works in javascript

我对运行以下函数的确切执行时间表有些困惑。 我在MDN指南上看到了以下代码:

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

根据我对功能如何工作的了解,这是我的想法,尽管我的知识不足:

我认为当调用函数foo(3) ,它将转到该函数并检查条件if i < 0 ,然后它将运行下一个代码console.log('begin:' + i)

之后,将执行下一行代码,由于JavaScript逐行执行,因此将执行下一行代码foo(i-1)

它采用i的当前值3减1,因此将调用foo(2)并继续执行。


我的问题是: 我的理解正确吗? 如果否,请解释该代码的作用,否则有人可以简短地解释何时停止调用该函数?

调用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

它是这样的:

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