Confusion in eloquent javascript power recursion sample

后端 未结 3 754
梦谈多话
梦谈多话 2021-01-25 16:29

this recursion code is from the book of eloquent javascript

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


        
3条回答
  •  一个人的身影
    2021-01-25 16:48

    What you have to notice is that the power function returns 1 when exponent is 0 and
    return base * power() on another case.

    Pay attention to power function

    In the following code

    power(base, exponent - 1);
    

    you have to appreciate some things

    1) If exponent is 1 the function power returns 1 so in here

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

    Whether base is 2

    return 2 * 1
    

    The function power is returning 2, so in the next step

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

    means

    return 2 * 2;
    

    which is 4, that means that function power is returning 4

    I think you can catch up from here.

    Let me know if you understood :)

提交回复
热议问题