简体   繁体   English

有人可以帮助我了解这段代码中发生了什么吗?

[英]can someone help me understand what is happening in this code?

Im struggling to understand what this calculation is return base * power(base, exponent - 1); 我正在努力理解这个计算是什么return base * power(base, exponent - 1); in the following code. 在以下代码中。 Does base get multiplied with the power function that has the base inside it again? 基数是否再次乘以具有基数的power函数?

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

power(2,2);

Does this mean that return base = 2*(2,2-1) ? 这是否意味着return base = 2*(2,2-1)

Does base get multiplied with the power function that has the base inside it again? 基数是否再次乘以具有基数的幂函数?

Yes, absolutely, and that's how this recursive implementation actually works. 是的,绝对如此,这就是递归实现的实际工作方式。

If you expand power(10, 4) for example you get: 例如,如果扩展power(10, 4) ,则会得到:

power(10, 4)
= 10 * power(10, 3)
= 10 * 10 * power(10, 2)
= 10 * 10 * 10 * power(10, 1)
= 10 * 10 * 10 * 10 * power(10, 0)
= 10 * 10 * 10 * 10 * 1

It should hopefully be clear from this expansion exactly why this is a valid (albeit slow) way to calculate exponents. 希望从这个扩展中可以清楚地知道为什么这是一种计算指数的有效方法(尽管很慢)。

It's 2 raised to the 0 power or 2 0 which is always 1. 它是2升到0的幂或2 0总是1。

It's a recursive method to calculate the exponents. 这是一种计算指数的递归方法。 Although Math.pow works better. 虽然Math.pow的效果更好。

So if the exponent is zero the recursion ends if (exponent === 0) return 1 . 因此,如果指数为零, if (exponent === 0) return 1则递归结束。 If the exponent is not zero. 如果指数不为零。 Then the method calls itself decrementing the exponent variable. 然后,该方法将调用自身以减小指数变量。

The magic happens return base * power(base, exponent - 1); 神奇的事情是return base * power(base, exponent - 1); once the method return 1; 一旦方法return 1; the values are pulled off the stack and multiplied by each other. 值从堆栈中拉出并彼此相乘。

This is not the best way to do this. 这不是执行此操作的最佳方法。

It is custom implementation of built-in method Math.pow . 它是内置方法Math.pow 自定义实现。 So these statements output same result: 因此,这些语句输出相同的结果:

console.log(power(2,8)); // 256
console.log(Math.pow(2, 8)); // 256

In case you need that, use Math.pow instead. 如果需要,请改用Math.pow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM