JavaScript 递归基本情况 [英] JavaScript recursion base case

查看:36
本文介绍了JavaScript 递归基本情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我知道这可能不是一个聪明的问题,但它让我发疯.鉴于这个递归函数,为什么 1 不是一直返回?我的意思是,指数最终会变为 0!

I'm sorry I know this is probably not a smart question but it's driving me crazy. Given this recursive function, why is 1 not returned all the time? I mean, eventually the exponent will get to 0!

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

非常感谢您的帮助.

推荐答案

理解的最好方法是遍历代码.假设你做 power(2,3).

The best way to understand is to walk through the code. Let's say you do power(2,3).

有什么作用?

2 * power(2,2) 
//Which expands to
2 * 2 * power(2,1)
//Which expands to
2 * 2 * 2 * power(2,0)
//Which expands to 
2 * 2 * 2 * 1

这篇关于JavaScript 递归基本情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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