在这个程序中,任何低于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));
}
如您所见,我尝试使用 age == NaN
触发字符串作为false
我也尝试进入age == String
.
当然,这会返回字符串的true
吗?
JavaScript 中有一点收获。 NaN == NaN
是false
,NaN === NaN
也是false
。如果要将某些内容与NaN
进行比较,请使用isNaN()
功能。
例:
if (age < 0 || age > MAX_AGE || isNaN(age))
inputError = true;
要检查年龄是否为 NaN,您需要调用函数 isNaN(age)
。 NaN == NaN
实际上是错误的。