Eloquent JavaScript递归示例如何作为返回1终止,但仍然输出指数值 [英] How does Eloquent JavaScript recursion example terminate as return 1 but still output exponential value

查看:88
本文介绍了Eloquent JavaScript递归示例如何作为返回1终止,但仍然输出指数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我完全了解它是如何工作的,直到终止和'返回1'。我假设一旦函数终止它应该输出1,但它会做你期望的指数程序做的,它输出正确的答案,在这种情况下是9.

In the code below I understand exactly how it works, right up until the termination and the 'return 1'. I would assume that once the function terminates it should output 1 but instead it does what you would expect an exponential program to do, it outputs the correct answer which in this case is 9.

我的问题是为什么会这样?

My question is why is this so ?

我假设我可视化递归的方式不正确(也许我对堆栈如何处理递归的看法?)我在这里发现了类似的问题但这对我的理解没有帮助。

I assume the way I visualize recursion is incorrect ( maybe my idea of how the stack treats recursion ?) I found a similar question to mine here but it doesn't help this one granular little inking of my understanding.

function power(base,exponent){

    if(exponent === 0){

        return 1   // Terminates with return 1 but output is correct 
    }

    return base * power(base, exponent-=1);
}

power(3,2)//输出9而不是1.为什么?

power(3,2) // This outputs 9 not 1. Why?

推荐答案

递归函数的工作方式如下:

The recursive function works like this:

首先,该函数将返回 3 * power(3,1)

现在你只调用该函数右边,所以只有这个价值必须解决才会变成。

Now you are only invoking the function at the right hand side, so only that value must resolve so it will become.

3 * 3 * power(3,0)

同样只有最正确的部分是必须解决的函数。

Again only the right most part is a function which must resolve.

所以它将是:

3*3*1

没有更多的函数可以解析,所以第一个函数为你提供结果 9

No more function is there to resole, so the first function provides you the result as 9.

它类似于

var x = multiple(3,1) * multiple(3,2) * multiple (3,4);

现在所有这些功能都将从左到右执行。

Now all those functions will execute from left to right.

因此,一旦所有函数被重新分配,x的值将被计算。

So once all functions are resoled, the value of x will be calculated.

这篇关于Eloquent JavaScript递归示例如何作为返回1终止,但仍然输出指数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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