[英]Factorial of a number in JavaScript throwing RangeError: Maximum call stack size exceeded
I want calculate factorial of a entered number on clicking a button but it throwing a RangeError.我想在单击按钮时计算输入数字的阶乘,但它会抛出 RangeError。
Here is my code it is working without the addEventListener
but with addEventListener it is throwing error:这是我的代码,它在没有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)......
Rather Than Making Code Complex Use This One As Factorial Of A Number By Onclick Event Instead而不是让代码变得复杂,而是通过 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>
This is because when the document is loaded, the value of the input
field is blank.这是因为在加载文档时, input
字段的值为空白。 When you try reading the value
of it and do parseInt()
it returns NaN
which is Not a Number
.当您尝试读取它的value
并执行parseInt()
时,它返回NaN
,它Not a Number
。 So, your solution will be to move it inside the addEventListener()
like this:-因此,您的解决方案是将其移动到addEventListener()
中,如下所示:-
factBtn.addEventListener("click", function(){
var factInput = parseInt(document.getElementById("fact").value);
document.getElementById("output2").innerHTML = factOfANumber(factInput);
});
Here's the entire js code:-这是整个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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.