我试图运行一个递归函数,它计算HTML输入上一个数字的阶乘。我已经知道如何通过迭代来实现它,我希望递归地实现这个结果。但是当我这样做的时候,我会得到一个“太多的递归”错误。我遗漏了什么?
<input type="text" name="factorial_input" placeholder="Enter a number">
<div class="button" onclick="calculateFactorial()">Let's see the factorial</div>JS
function calculateFactorial(getInputValue) {
getInputValue = document.querySelector("input").value;
if (!getInputValue) {
console.log("You must enter a number");
} else if (getInputValue == 0) {
return console.log("1");
} else {
return console.log(getInputValue *= calculateFactorial(getInputValue - 1));
}
// console.log(getInputValue);}
发布于 2020-02-08 03:40:17
您会遇到没完没了的递归问题,因为您正在从递归函数中的输入中检索值,这就是为什么getInputValue变量每次都获得新值的原因。这是你做的错误的实现。试试下面给出的例子。
HTML
<input type="text" name="factorial_input" placeholder="Enter a number">
<div class="button" onclick="calculateFactorial()">Let's see the factorial</div>剧本
function calculateFactorial(getInputValue) {
let getInputValue = parseInt(document.querySelector("input").value);
console.log(fact(getInputValue));
}
function fact(n){
if (n === undefined) {
return 0;
} else if (n === 0) {
return 1;
} else {
return n *= fact(n - 1);
}
}递归函数需要一个满意的条件才能从反求函数返回调用堆栈。否则,就会有没完没了的电话。
发布于 2020-02-08 02:59:51
如果您没有将getInputValue传递给函数,为什么要将它作为函数参数呢?
不要把事情混在一起,这只会使事情更难理解。
相反,创建一个只计算阶乘值的阶乘函数,将输入的值传递给函数,然后console.log()将其输出。
function factorial(number) {
return number == 1 || number == 0 ? number : number * factorial(number - 1);
}https://stackoverflow.com/questions/60123434
复制相似问题