我正在研究JavaScript计算器,其中冰球守门员将能够输入信息来计算他的平均目标数或他的GAA。我已经使用了计算器(尽管我希望我可以将输出格式化为#。##,但是很好),但是我希望能够处理例如用户输入一个字母而不是数字引起的异常,这会通过try/catch语句产生NaN输出,除非我不确定如何格式化它以查找NaN值。任何想法我会怎么做呢?这里是我的代码:JavaScript中的NaN值的尝试/捕获声明
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Goals Against Average Calculator</Title>
<body>
<script src="modernizr.custom.05819.js"></script><!--Links to file containing modernizer library-->
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li><a href="file:///C:/Users/Kyle/Desktop/Document1.html">Home</a></li> <!--Link to Home Page-->
<li><a href="file:///C:/Users/Kyle/Desktop/Document2.html">NHL Teams</a></li><!--Link to Page of NHL Teams-->
<li><a href="file:///C:/Users/Kyle/Desktop/Document3.html">AHL Teams</a></li><!--Link to Page of AHL Teams-->
<li><a href="file:///C:/Users/Kyle/Desktop/Document4.html">WHL Teams</a></li><!--Link to Page of WHL Teams-->
<li><a href="file:///C:/Users/Kyle/Desktop/Document5.html">G.A.A. Calculator</a></li><!--Link to GAA Calculator-->
<li><a href="file:///C:/Users/Kyle/Desktop/Document6.html">Fan Survey</a></li><!--Link to Fan Survey Page-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Goals Against Average Calculator</h1><!--Title of Page-->
</header>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p id="GAA"> </p>
</fieldset>
</form>
</article>
<script>
function convert()
{
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MPlayed").value;
var GameLength = document.getElementById("MinGame").value;
var GAA = (Goals * GameLength)/Minutes;
//window.alert("Swords and Sandals: " + GAA);
document.getElementById("GAA").innerHTML = "Your Goals Against Average is: " + GAA;
}
document.getElementById("button").
addEventListener("click", convert, false);
</script>
</body>
</html>
编辑:关于小数格式的评论不是我发布的原因。这仅仅是出于美观的原因,我希望它看起来像什么,但它的效果很好。
使用[parseInt()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt)和[isNaN()](https://developer.mozilla.org/EN /文档/网络/的JavaScript /参考/ Global_Objects/isNaN)。 – Nit
只需在此行后面检查'isNaN(GAA)'var GAA =(目标* GameLength)/分钟;' –
可能的重复[验证JavaScript中的十进制数字 - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) –