简体   繁体   中英

What is the variable result doing in this javascript function

In the code below, if result is set to one, the code returns a number 1024 (2 to the power of 10). If result is set to 2, the code returns the number 2048 (or 2 to the power of 11), BUT if result is set to 3, the code doesn`t return the number 4096 (as I would expect, because 2 to the power of 12) but rather 3072. Why does it return 3072 if "result" is set to 3, but otherwise if set to 1 and 2 it followers the pattern of power to the 10th and 11th

function power(base, exponent) {
  var result = 1;
  for (var count = 0; count < exponent; count++)
    result *= base;
  return result;
}

show(power(2, 10));

In this code, result is used as an accumulator. The code computes result * base**exponent ; result is not part of the exponent.

I think you're confusing yourself. The thing being raised to some power is your first parameter (in your example 2). The exponent is the 2nd parameter (10). Your example works correctly. Pass in 12 as your exponent and you will see your expected result.

The result parameter is just a place holder in which you accumulate your results (2x2x2x2....)

The numbers doing all the work are the ones you pass in as parameters to the function.

So, in your example, you're going to take 2 and multiply it by itself 10 times, each time storing the cumulative result in the variable "result". The thing that's throwing you off is that result is initially set to 1. This is never meant to be altered. It's built that way so that if you set your exponent to 0 you will end up with a result of 1 (because any number raised to the zeroth power = 1).

Anyway... don't worry about what result is set to. Focus on how the loop works with the interchangeable variable values that are being passed in, in the function call.

Do out the multiplication:

  1. 3 * 2 = 6
  2. 6 * 2 = 16
  3. 12 * 2 = 24
  4. 24 * 2 = 48
  5. 48 * 2 = 96
  6. 96 * 2 = 192
  7. 192 * 2 = 384
  8. 384 * 2 = 768
  9. 768 * 2 = 1536
  10. 1536 * 2 = 3072

Multiplication table perhaps? Also, what's wrong with Math.pow , just trying to accomplish it yourself?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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