JavaScript遞歸

了解JavaScript中的遞歸基礎

一個函數可以調用自己

這就是遞歸的意思。它使我們能夠以一種簡潔的方式解決問題。

為此,您需要一個命名函數表達式,換句話說,這是:

function doSomething() {

}

所以我們可以打電話doSomething()裡面doSomething()

The simplest example we can make is calculating a factorial of a number. This is the number that we get by multiplying the number for (number - 1), (number - 2), and so on until we reach the number 1.

4的階乘為(4 *(4-1)*(4-2)*(4-3))= 4 * 3 * 2 * 1,即24。

我們可以創建一個遞歸函數來自動計算它:

function factorial(n) {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1 factorial(2) //2 factorial(3) //6 factorial(4) //24

如果願意,我們還可以使用箭頭功能:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1 factorial(2) //2 factorial(3) //6 factorial(4) //24

現在是時候談論調用堆棧

想像我們犯了一個錯誤,而不是將階乘計算為

const factorial = (n) => {
  return n >= 1 ? n * factorial(n - 1) : 1
}

我們這樣做:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n) : 1
}

如您所見,我們正在致電factorial(n)廣告無限。沒有盡頭,因為我們忘了每次通話都降低它。

如果運行此代碼,則會出現以下錯誤:

RangeError: Maximum call stack size exceeded

Every time a function is invoked, JavaScript needs to remember the current context before switching to the new one, so it puts that context on the call stack. As soon as the function returns, JavaScript goes to the call stack and picks the last element that was added, and resumes its execution.

Maximum call stack size exceeded means that too many elements were put on the stack, and your program crashed.


More js tutorials: