在此程序中,输入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;
关于javascript - 对于字符串 返回 false 的 boolean 值 - 需要为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057567/