簡體   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