我试图计算用户在html脚本中提供的输入的总薪水。我总是得到一个未定义的总薪酬结果。我尝试从第二个脚本标记中调用calculate_pay函数,但这并没有改变任何内容。我做错了什么?
<!DOCTYPE html>
<head>
<title>Chapter 4 Assignment</title>
<script>
function input_output(netPay)
{
var hoursWorked = prompt("How many hours have you worked?","");
var payRate = prompt ("What is your hourly pay rate?","");
var taxRate = prompt ("What is the tax rate for your state? ex. 11 for 11%","");
var br = "<br>";
document.write("Hours worked: "+hoursWorked+br);
document.write("Pay rate: "+payRate+br);
document.write("Tax rate: "+taxRate+br);
document.write("Total pay: "+netPay+br);
}
function calculate_pay(hoursWorked,payRate,taxRate)
{
var taxRate = taxRate/100;
var grossPay = (hoursWorked*taxRate);
var netPay = grossPay - (taxRate * grossPay);
return netPay;
}
</script>
</head>
<body>
<script>
input_output();
</script>
</body>
</html>
我尝试在input_output中调用calculate_pay函数,如下所示:
function input_output(netPay)
{
var hoursWorked = prompt("How many hours have you worked?","");
var payRate = prompt ("What is your hourly pay rate?","");
var taxRate = prompt ("What is the tax rate for your state? ex. 11 for 11%","");
var br = "<br>";
calculate_pay();
document.write("Hours worked: "+hoursWorked+br);
document.write("Pay rate: "+payRate+br);
document.write("Tax rate: "+taxRate+br);
document.write("Total pay: "+netPay+br);
}
除了在第二个脚本标签中同时调用它,但它仍然返回undefined。
答案 0 :(得分:0)
我认为你想要这样的东西:
function input_output() {...} // get rid of the input parameter
在var taxRate行之后添加:
var netPay = calculate_pay(hoursWorked, payRate, taxRate);
答案 1 :(得分:0)
您只是调用input_output()
功能,该功能会提示用户hoursWorked
,payRate
和taxRate
,但从不计算任何内容。 input_output()
,netPay
的参数可能放错了位置。您应该调用函数calculate_pay()
来实际获得该值。
第一个函数的最后一行应该是
document.write("Total pay: " + calculate_pay(hoursWorked,payRate,taxRate) + br);
但在到达那里之前,您必须注意使用parseFloat将输入值从String
转换为Number
。也就是说,对于您拥有的每个提示,请执行以下操作:
var hoursWorked = parseFloat(
prompt("How many hours have you worked?","")
);
无论用户类型始终为String
,因此请务必使用Number
方法将这些字符串值转换为实际parseFloat()
。