我有这个脚本提示使用dinnerCost和taxRate来生成taxPaid。我想创建一个if语句,确保只输入整数而不是字符串。
这是我的代码:
<button id="btn"> Play the Dinner Game </button>
<p id="para"></p>
document.getElementById("btn").addEventListener("click", dinnerThing);
function dinnerThing () {
var cost = prompt("how much did it cost?");
if(cost == "") {
document.getElementById("para").innerHTML = "sorry please enter an integer";
}
var taxRate = prompt("What was the tax rate?");
if(taxRate == "") {
document.getElementById("para").innerHTML = "sorry please enter an integer";
}
var taxPaid = cost * taxRate;
document.getElementById("para").innerHTML = "You paid " + taxPaid + " dollars in tax for your dinner";
}
为什么if语句不能在这里工作?
答案 0 :(得分:0)
if(cost == "")
和if(taxRate == "")
都是 检查是否 变量(cost1 or
taxRate`)等于空字符串,而不是它 等于整数 。
要确保您从提示号码中收到值,您可以使用parseInt()。
parseInt()将从字符串返回Number(整数或浮点数)等价物。如果字符串无法转换为数字,则返回NaN。
步骤将是:
获取cost和taxRate的parseInt()值,将它们存储在变量中
使用isNaN()检查先前变量中的任何一个是否返回NaN。
如果isNaN()
返回true
,则显示“抱歉,请输入整数”消息
如果isNaN()
返回false
,则计算taxPaid和输出taxPaid值
结果代码如下所示:
var numberCost = parseInt(cost),
numberTaxRate = parseInt(taxRate);
if(isNaN(numberCost) || isNaN(numberTaxRate)) {
document.getElementById("para").innerHTML = "sorry please enter an integer";
}else{
var taxPaid = cost * taxRate;
document.getElementById("para").innerHTML = "You paid " + taxPaid + " dollars in tax for your dinner";
}