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: