【问题标题】:Performing recursive function on input javascript对输入的javascript执行递归函数
【发布时间】:2020-02-08 02:35:05
【问题描述】:

我正在尝试运行一个递归函数来计算 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);

}

【问题讨论】:

    标签: javascript html recursion input


    【解决方案1】:

    您遇到了无穷无尽的递归问题,因为您正在从递归函数的输入中检索值,这就是为什么 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返回调用栈。否则,它会去无休止的调用。

    【讨论】:

    • 好的,谢谢!我没有想到在另一个函数中使用函数调用。很有帮助
    【解决方案2】:

    如果你不将它传递给函数,为什么你将 getInputValue 作为函数参数?

    不要把事情混在一起,这只会让事情变得更难理解。

    改为创建一个只计算阶乘值的阶乘函数,将输入的值传递给函数,然后 console.log() 将其输出。

    function factorial(number) {
      return number == 1 || number == 0 ? number : number * factorial(number - 1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2020-04-17
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多