首页 > 解决方案 > 对输入的javascript执行递归函数

问题描述

我正在尝试运行一个递归函数来计算 HTML 输入中数字的阶乘。我已经知道如何通过迭代来做到这一点,我想递归地实现结果。但是当我这样做时,我得到一个“递归过多”的错误。我错过了什么?

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);

}

标签: javascripthtmlrecursioninput

解决方案


您遇到了无穷无尽的递归问题,因为您正在从递归函数的输入中检索值,这就是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);
    }
}

递归函数需要满足条件才能从recursion返回调用栈。否则,它会去无休止的调用。


推荐阅读