gpt4 book ai didi

javascript - Eloquent JavaScript 递归返回?

转载 作者:行者123 更新时间:2023-11-28 18:33:43 27 4
gpt4 key购买 nike

我很难理解 Eloquent JavaScript 中的递归,很容易知道发生了什么,但我不明白为什么......

function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1); /* 2*2*2, this returns only base?
i thought at first it was, 2*(2,3-1) so it would return 2*(2,2)?
calling itself until reach 0, so why exponent is out?*/
}

console.log(power(2, 3));
// → 8

最佳答案

递归函数通常可以表示为循环。请参阅此改编:

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

正如您所看到的,指数在输出中根本不起作用,它仅表示要进行的循环数。

在递归世界中,指数表示函数在返回之前尚未调用自身的次数。

这个 YouTube 视频很好地可视化了递归:Computerphile

关于javascript - Eloquent JavaScript 递归返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37502727/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com