布尔值为字符串返回false - 需要为true

时间:2017-11-01 14:49:34

标签: javascript if-statement input boolean user-input

在此计划中,0或以上121以下的任意数字或字符串的输入应返回为'Invalid Input'。但是,输入字符串时,将返回FULL_PRICE字符串。

const LOW_AGE = 5,
  HIGH_AGE = 69,
  MID_AGE = 17,
  MAX_AGE = 120,
  FULL_PRICE = "You must pay full price.",
  HALF_PRICE = "You must pay half price.",
  FREE = "You may travel for free";

function main() {
  var age, inputError, cost;

  age = Number(prompt("Enter Your Age:"));

  if (age < 0 || age > MAX_AGE || age == NaN)
    inputError = true;
  else
    inputError = false;

  if (age < LOW_AGE || age > HIGH_AGE)
    cost = FREE;
  else if (age < MID_AGE)
    cost = HALF_PRICE;
  else
    cost = FULL_PRICE;

  if (inputError)
    alert("Input Error.");
  else
    alert(String(cost));
}

正如您所见,我尝试使用false将字符串作为age == NaN触发。

我还尝试输入age == String

肯定会为true返回一个字符串?

2 个答案:

答案 0 :(得分:5)

JavaScript中有一点点。 NaN == NaN falseNaN === NaN也是false。如果您想将某些内容与NaN进行比较,请使用isNaN()函数。

示例:

if (age < 0 || age > MAX_AGE || isNaN(age)) 
  inputError = true;

答案 1 :(得分:0)

要检查年龄是否为NaN,您需要调用函数isNaN(age)NaN == NaN实际上是假的。