javascript递归_JavaScript递归

javascript递归

A function can call itself.

一个函数可以调用自己

This is what recursion means. And it allows us to solve problems in a neat way.

这就是递归的意思。 它使我们能够以一种简洁的方式解决问题。

To do so, you need a named function expression, in other words this:

为此,您需要一个命名函数表达式,换句话说:

function doSomething() {

}

So we can call doSomething() inside 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.

我们可以做的最简单的示例是计算数字的阶乘。 这是通过将(number-1),(number-2)等等的数字相乘得到的数字,直到达到数字1。

The factorial of 4 is (4 * (4 - 1) * (4 - 2) * (4 - 3)) = 4 * 3 * 2 * 1, which is 24.

4的阶乘是(4 *(4-1)*(4-2)*(4-3))= 4 * 3 * 2 * 1,即24。

We can create a recursive function to calculate it automatically:

我们可以创建一个递归函数来自动计算它:

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

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

We can also use an arrow function if we prefer:

如果愿意,我们还可以使用箭头功能:

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

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

Now it’s a good time to talk about the call stack.

现在是讨论调用堆栈的好时机。

Imagine we do an error, and instead of calculating the factorial as

想象我们犯了一个错误,而不是将阶乘计算为

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

we do this:

我们这样做:

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

As you can see, we are calling factorial(n) ad infinitum. There’s no end, because we forgot to lower it on every call.

如您所见,我们无限次调用factorial(n) ad。 没有尽头,因为我们忘了每次通话都降低它。

If you run this code, you’ll get this error:

如果运行此代码,则会出现以下错误:

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.

每次调用一个函数时,JavaScript都需要在切换到新函数之前记住当前上下文,因此它将该上下文放在调用堆栈中 。 函数返回后,JavaScript会转到调用堆栈并选择最后添加的元素,然后继续执行。

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

超出最大调用堆栈大小意味着堆栈中放置了太多元素,程序崩溃了。

翻译自: https://flaviocopes.com/javascript-recursion/

javascript递归

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值