雄辩的 javascript 幂递归示例中的混淆 [英] Confusion in eloquent javascript power recursion sample

查看:36
本文介绍了雄辩的 javascript 幂递归示例中的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个递归代码来自eloquent javascript的书

this recursion code is from the book of eloquent javascript

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

console.log(power(2, 3));

很明显指数是减少到0,如果不是0,就在栈上增加power call,如果是0,我开始看到1然后2然后4然后8的返回值.但是怎么做base 是否乘以指数,base 是如何看到指数值的?是在其他还是在通电?

obviously the exponent is decreased until it reached 0, if it is not zero, it adds power call on the stack, if it is zero, I start to see the return value of 1 then 2 then 4 then 8. But how did base got multiplied by exponent, how did base see the exponent value? it's on else and on power call?

推荐答案

但是基数是如何乘以指数的

它不会乘以指数.

exponent 被用作计数器,一旦它被减少到 0 就结束递归循环.base 被自身乘以 exponent 次.

The exponent is being used as a counter to end the recursive cycle once it's been reduced to 0. The base is instead being multiplied by itself an exponent number of times.

每次调用 power() 都会返回 1base 的值.在后一种情况下,再次调用 power() 以得到 1base 的另一个副本以乘以.而且,这会重复,直到它最终返回 1 作为最终乘数.

This is supported by each call to power() returning either 1 or the value of base. In the latter case, power() is called again to get 1 or another copy of base to multiply by. And, this repeats until it does finally return 1 as the final multiplier.

            power(2, 3) ==
        2 * power(2, 2) == // base * ...
    2 * 2 * power(2, 1) == // base * (base * ...)
2 * 2 * 2 * power(2, 0) == // base * (base * (base * ...))
2 * 2 * 2 * 1              // base * (base * (base * (1)))

<小时>

同样的步骤也可以用循环定义,但使用 1 作为初始值而不是最后:


The same steps could also be defined with a loop, though using 1 as the initial value rather then at the end:

function power(base, exponent) {
    var result = 1;

    while (exponent) {
        result *= base;
        exponent--;
    }

    return result;
}

console.log(power(2, 3)); // 1 * base * base * base == 1 * 2 * 2 * 2 == 8

这篇关于雄辩的 javascript 幂递归示例中的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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