Factorial of a number in JavaScript throwing RangeError: Maximum call stack size exceeded

Factorial of a number in JavaScript throwing RangeError: Maximum call stack size exceeded

我想在单击按钮时计算输入数字的阶乘,但它会引发 RangeError。

这是我的代码,它在没有 addEventListener 的情况下工作,但是使用 addEventListener 时它会抛出错误:

var factInput = parseInt(document.getElementById("fact").value);
var factBtn = document.getElementById("btnFactorial");

factBtn.addEventListener("click", function() {
  document.getElementById("output2").innerHTML = factOfANumber(factInput);
})

function factOfANumber(n) {
  var fact = 0;
  if (n === 1) {
    return n;
  } else {
    fact = n * factOfANumber(n - 1);
  }
  return fact;
}
<div id="FactorialNumber">
  <h1>2. Factorial of a Number</h1>
  <input type="number" id="fact" placeholder="Enter a Number"></input>
  <button id="btnFactorial">Give me Factorial</button>
  <p>Output:</p>
  <p id="output2"></p>
  <hr>

</div>

home.js:13 Uncaught RangeError: Maximum call stack size exceeded
    at factOfANumber (home.js:13)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)......

与其让代码变得复杂,不如通过 Onclick 事件使用这个作为数字的阶乘

 <!doctype html>
    <html>
    <head>
    <script>
    function show(){
    
    var i, no, fact;
    fact=1;
    no=Number(document.getElementById("num").value);
    for(i=1; i<=no; i++)  
    {
    fact= fact*i;
    }  
    document.getElementById("answer").value= fact;
    }
    </script>
    </head>
    <body>
    Enter Num: <input id="num">
    <button onclick="show()">Factorial</button>
    <input id="answer">
    </body>
    </html>

output

这是因为加载文档时,input 字段的值为空。当您尝试阅读它的 value 并执行 parseInt() 时,它 returns NaNNot a Number。因此,您的解决方案是将其移动到 addEventListener() 内,如下所示:-

factBtn.addEventListener("click", function(){
    var factInput = parseInt(document.getElementById("fact").value);
    document.getElementById("output2").innerHTML = factOfANumber(factInput);
});

这是完整的js代码:-

var factBtn = document.getElementById("btnFactorial");
factBtn.addEventListener("click", function(){
    var factInput = parseInt(document.getElementById("fact").value);
    document.getElementById("output2").innerHTML = factOfANumber(factInput);
})
function factOfANumber(n){
    var fact = 0;
    if(n===1){
        return n;
    }
    return n * factOfANumber(n-1);
}