JavaScript 中数字的阶乘抛出 RangeError:超出最大调用堆栈大小
2021-05-25
263
我想在单击按钮时计算输入数字的阶乘,但它引发了 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)......
2个回答
不要让代码变得复杂,而是通过 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>
Yash Chitroda
2021-05-25
这是因为在加载文档时,
input
字段的值为空。当您尝试读取它的
value
并执行
parseInt()
时,它会返回
NaN
,即
Not 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);
}
Rohan
2021-05-25