我最近启动了JavaScript,并且正在开发一个简单的税计算器,我唯一的问题是输出返回undefined
而不是期望值。例如,当我输入320000时,所得税应为14000,但它返回的是undefined。我尝试将calculation
设置为0
,但是并不能解决问题。是什么使我的函数不返回期望值?我看过我的大学给出的示例程序,这些程序在条件中使用变量,它们可以正常工作,但我的不是。
function calculateTax()
{
var taxableIncome, calculation;
taxableIncome = document.getElementById("t").value * 1;
if (taxableIncome > 250000) {
calculation = 0;
}
else if (taxableIncome > 250000 && taxableIncome < 40000) {
calculation = (taxableIncome - 250000) * 0.20;
}
else if (taxableIncome > 400000 && taxableIncome < 800000) {
calculation = ((taxableIncome - 400000) * 0.25) + 30000;
}
else if (taxableIncome > 800000 && taxableIncome < 2000000) {
calculation = ((taxableIncome - 800000) * 0.30) + 130000;
}
else if (taxableIncome > 2000000 && taxableIncome < 8000000) {
calculation = ((taxableIncome - 2000000) * 0.32);
}
else if (taxableIncome > 8000000) {
calculation = ((taxableIncome - 8000000) * 0.35) + 2410000;
}
document.getElementById("inputTax").innerHTML = "The taxable income is:" +taxableIncome;
document.getElementById("incomeTax").innerHTML = "The income tax is:" +calculation;
}
<h1>Income Tax Calculator</h1>
<p>
<label for = "t">Taxable Income</label>
<input type = "number" id="t" name="t">
<button onclick = "calculateTax()"> Calculate Tax </button>
</p>
<h2 id="inputTax"></h2>
<h2 id="incomeTax"></h2>
答案 0 :(得分:1)
对于值320000
,对于taxableIncome > 250000
,条件始终为 true ,并返回0
。此外,值40000
(在第二种情况下使用)和400000
(在第三种情况下使用)之间不匹配。
您应将以下前两个条件更改为:
if (taxableIncome < 250000) {
else if (taxableIncome > 250000 && taxableIncome < 400000) {
请注意::您不需要检查最终条件(taxableIncome > 8000000
),只需else
就可以。
演示:
function calculateTax()
{
var taxableIncome, calculation;
taxableIncome = document.getElementById("t").value * 1;
if (taxableIncome < 250000) {
calculation = 0;
}
else if (taxableIncome > 250000 && taxableIncome < 400000) {
calculation = (taxableIncome - 250000) * 0.20;
}
else if (taxableIncome > 400000 && taxableIncome < 800000) {
calculation = ((taxableIncome - 400000) * 0.25) + 30000;
}
else if (taxableIncome > 800000 && taxableIncome < 2000000) {
calculation = ((taxableIncome - 800000) * 0.30) + 130000;
}
else if (taxableIncome > 2000000 && taxableIncome < 8000000) {
calculation = ((taxableIncome - 2000000) * 0.32);
}
else{
calculation = ((taxableIncome - 8000000) * 0.35) + 2410000;
}
document.getElementById("inputTax").innerHTML = "The taxable income is:" +taxableIncome;
document.getElementById("incomeTax").innerHTML = "The income tax is:" +calculation;
}
<h1>Income Tax Calculator</h1>
<p>
<label for = "t">Taxable Income</label>
<input type = "number" id="t" name="t">
<button onclick = "calculateTax()"> Calculate Tax </button>
</p>
<h2 id="inputTax"></h2>
<h2 id="incomeTax"></h2>