[英]Question about recursive JS - from freecodecamp
有這個function:
function countup(n) { if (n < 1) { return []; } else { const countArray = countup(n - 1); countArray.push(n); return countArray; } } console.log(countup(5));
[] 是如何被先推送的? 從代碼看,好像是從 n 開始倒計時。 有人可以解釋嗎?
額外的問題:當我可以寫時為什么要這樣寫:
function countup(n){ let answer = [] for (let i = 1; i <= n; i++){ (i<n)? answer.push(i): answer.push(n) } return answer } console.log(countup(5));
這是一個較短的 function。 先感謝您!
即使數字從n
開始按降序排列,它們實際上是首先被推入最小的數字。 這是因為在push()
操作發生之前,當我們在遞歸的每一層調用countup(n - 1)
時,我們一直在遞歸堆棧中下降。 這就是為什么我們會達到n < 1
即0
返回空數組的點。
接下來,我們遇到第一個array.push()
操作,因此推入數組的第一個數字實際上是 1 而不是n
。 接下來,遞歸層開始結束,我們將數字 2、3 等推入n
。
是的,您可以使用傳統的 for 循環實現相同的目的,但我想他們只是想解釋遞歸的工作原理。
要理解遞歸,有時您需要手動跟蹤代碼的執行。 現在下面的行導致遞歸調用並從數字中減一,然后將其傳遞給遞歸調用。
const countArray = countup(n - 1);
現在想象一下,如果您將5
傳遞給最初的 function 調用,如下所示:
countup(5);
由於 5 不小於 1, else
塊將被執行。 else
塊中的第一行是遞歸調用。 因此,當您的程序遇到遞歸調用時,它會停止當前 function 的執行,直到該遞歸 function 調用結束/返回。 所以第一個遞歸調用將是:
const countArray = countup(4);
因此,將重復相同的過程,直到n
等於 0。由於0
小於 1, if
條件將評估為true
。 它將返回一個empty array
。
遞歸調用后,將數字推送到遞歸調用返回的數組中。 所以該點的數組將包含[0]
然后[0, 1]
並且它將繼續添加數字,直到計算出所有遞歸調用,然后它將執行初始 function 調用的 rest。
很多時候,遞歸可以被循環代替,但情況並非總是如此。 作為一名程序員,應該意識到這個重要的話題。
由於countup()
完全除以依賴於n
的 if 語句,讓我們首先看看n
的不同值執行什么。
為了更容易理解,我們將 append 我們當前的n
到countArray
的變量名:
n == 5:
const countArray5 = countup(4);
countArray5.push(5);
return countArray5;
⋮
n == 1:
const countArray1 = countup(0);
countArray1.push(1);
return countArray1;
n == 0:
return [];
現在讓我們依次展開對countup(n)
的每個內部調用:
countup(5) {
const countArray5 = countup(4);
countArray5.push(5);
return countArray5;
}
countup(5) {
const countArray5 = countup(4) {
const countArray4 = countup(3);
countArray4.push(4);
return countArray4;
};
countArray5.push(5);
return countArray5;
}
展開直到countup(0)
:
countup(5) {
const countArray5 = countup(4) {
const countArray4 = countup(3) {
const countArray3 = countup(2) {
const countArray2 = countup(1) {
const countArray1 = countup(0) // countup(0) returns [] so countArray1 = [];
countArray1.push(1); // Then push '1' to countArray1;
return countArray1; // Return [1] at counterArray2 = countup(1) above
};
countArray2.push(2); // countArray2 was [1], now push '2' to make it [1,2]
return countArray2; // Return [1,2] at countArray3 = countup(2) above
};
countArray3.push(3); // Push '3' to countArray3 => [1,2,3]
return countArray3; // return [1,2,3] at countArray4 = countup(3)
};
countArray4.push(4); // Push '4' to countArray4 => [1,2,3,4]
return countArray4; // Return [1,2,3,4] at countArray5 = countup(4)
};
countArray5.push(5); // Push '5' to countArray5 => [1,2,3,4,5]
return countArray5; // countup(5) returns [1,2,3,4,5]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.