简体   繁体   English

简单的晚餐小费计算器的Javascript If语句

[英]Javascript If statement for simple dinner tip calculator

I have this script that prompts for dinnerCost and taxRate to generate taxPaid. 我有这个脚本,提示DinnerCost和taxRate生成taxPaid。 I want to make an if statement that makes sure that only integers are entered not strings. 我想做一个if语句,以确保只输入整数而不输入字符串。

here is my code: 这是我的代码:

<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";
}

Why is if statement not working here? 为什么语句在这里不起作用?

Both if(cost == "") and if(taxRate == "") are checking if the variable ( cost1 or taxRate`) is equal to an empty string, not if it is equal to an integer . if(cost == "")if(taxRate == "")都在检查变量( cost1 or taxRate`)是否等于空字符串,而不是是否等于整数

To ensure that you receive a value from prompt that is an Number you can use parseInt() . 为了确保您从提示符处收到一个数字值,可以使用parseInt()

parseInt() will return a Number (integer or float) equivalent from a string. parseInt()将从字符串返回等效的Number(整数或浮点数)。 If the string cannot be converted into a number, it returns NaN. 如果字符串不能转换为数字,则返回NaN。

The steps would then be: 步骤如下:

  • get parseInt() values for cost and taxRate, store them in variables 获取cost和taxRate的parseInt()值,并将它们存储在变量中

  • check if either of the previous variables returns is NaN using isNaN() . 使用isNaN()检查先前的变量是否返回的是NaN。

  • If isNaN() returns true , then display "sorry please enter an integer" message 如果isNaN()返回true ,则显示“对不起,请输入整数”消息

  • If isNaN() returns false , then calculate taxPaid and output taxPaid value 如果isNaN()返回false ,则计算taxPaid并输出taxPaid值

The resulting code would look something like this: 结果代码如下所示:

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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM