我正在为课程编写这个基本的控制结构,我得到了一些意外的行为。
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
在最后一个有条件的条件下,我希望如果我的提示为空,它将执行最后一个警报。但是,它只是说"不够大"。是否将提示中的输入不视为0?如何解决此问题?
谢谢。
提示如果用户命中正常,则不会返回 null
,以测试空虚,您需要检查字符串是否为空answer === ""
您需要将最后两个检查移至顶部,因为"" < 21
是true
:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}