我是JavaScript新手。對於我的任務之一,我必須爲我的班級編寫JavaScript代碼,以確定並顯示用戶輸入收入的稅額。到目前爲止,我的代碼如下所示:如何檢查少於一個的數字和JavaScript中的非數字?
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tax Assignment</title>
</head>
<body>
<script>
//declare variables and collect amount enter.
// Assign amount entered to var amountEntered.
var amountEntered = window.prompt("Enter an income amount in dollars");
var x = parseInt(amountEntered);
var untaxableIncome = 12000;
var taxBracketOne = 36000;
var taxBracketTwo = 90000;
var bracketOneTax = 0.15;
var bracketTwoTax = 0.25;
var total;
//determine if the number is less than one
if (x < 1)
{
alert("Enter a whole number greater than 0");
}
//
else if (x == NaN)
{
alert("Enter a whole number greater than 0");
}
else if (x <= untaxableIncome)
{
alert("You will not be charged taxes on your income");
}
else if (x >untaxableIncome && x <= taxBracketOne)
{
total = amountEntered * bracketOneTax;
document.write("You will need to pay " + total + " on your " + amountEntered + " income.")
}
else if (x > taxBracketOne && x <= taxBracketTwo)
{
total = amountEntered * bracketTwoTax;
document.write("You will need to pay " + total + " on your " + amountEntered + " income.")
}
else (x > taxBracketTwo)
{
document.write("I do not have the data to calculate the tax on this income.")
}
</script>
</body>
</html>
的計算工作得很好,我有唯一的問題是,當我輸入.5或字母,我沒有得到警報(「請輸入一個整數大於0「);我究竟做錯了什麼?
此外,我怎麼做的提示框中再次,如果用戶出現已輸入小於1的字母或數值? – nponinski
您正在使用ParseInt。它不識別字符或小數值。小於1的字母或數值(如.5)將爲零,不小於零。 –
爲了一致性,我更願意使用'Math.floor(Number(x))'來截斷小數,而不是'parseInt(x)'。此外,JavaScript中沒有值是'=='或'==='到'NaN',包括'NaN'本身。爲此,有一個內置函數isNaN()。 – mhodges