JavaScript输出返回未定义



我最近启动了JavaScript,并一直在开发一个简单的税收计算器,唯一的问题是输出返回undefined,而不是预期值。例如,当我输入320000时,所得税应该是14000,但它返回未定义。我尝试将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>

对于值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>

相关内容

  • 没有找到相关文章

最新更新