此递归函数在JavaScript中到底如何工作? [英] How exactly does this recursive function work in JavaScript?

查看:57
本文介绍了此递归函数在JavaScript中到底如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下递归函数示例,但我不了解事情发生的顺序:

I have the following example of a recursive function, and what I don't understand is the order in which things are happening:

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

该函数何时在所有过程结束时或每次返回值?

When does the function return the values, at the end of all the process or each time?

推荐答案

一种可视化递归一般情况的简单方法是:

A simple way to visualize what happens in recursion in general is this:

  1. 该函数的调用的堆栈已创建:该过程需要适当的终止条件才能结束(否则,您将具有无限递归,即 evil )
  2. 单个结果从堆栈中弹出 :每个结果都用于计算下一步,直到堆栈为空
  1. a stack of calls to the function is created: this process needs a proper termination condition to end (otherwise you'll have infinite recursion, which is evil)
  2. the single results are popped out of the stack: each result is used to calculate the next step, until the stack is empty

即如果base = 5和exponent = 3,则调用堆栈为(最后一个元素在顶部):

I.e. if base=5 and exponent=3, the call stack is (last element on top):

5*(5*(5*1))
5*(5*(5*power(5, 0)))
5*(5*power(5, 1))
5*power(5, 2)
power(5, 3)

然后每个被调用的函数都有实际参数,并准备返回值(第一个元素在顶部):

then every called function has real parameters and is ready to return a value (first element on top):

5*(5*(5*1))
5*(5*5)
5*25
125

请注意,这里的功能是按 inverse 的顺序进行计算的:首先是power(5, 0),然后是power(5, 1),依此类推..每次计算之后,都会释放堆栈中的一个元素(即,内存被释放).释放).

Note that here the functions are calulated in inverse order: first power(5, 0), then power(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).

希望它会有所帮助:)

这篇关于此递归函数在JavaScript中到底如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆