Javascript 如何在提示窗口中区分空字符串和空字符串?
我必须检查(提示窗口是必需的)用户是否在以下条件下输入了正确答案:Javascript 如何在提示窗口中区分空字符串和空字符串?,javascript,prompt,Javascript,Prompt,我必须检查(提示窗口是必需的)用户是否在以下条件下输入了正确答案: 如果用户输入了正确答案,请提醒“您是正确的” 如果用户输入错误答案或将其留空,请提醒“您错了” 3如果用户按下“取消”按钮,则不会发生任何事情 结果是,即使我按下取消键,警报也会显示“你错了”。我添加的取消警报只是一个例子。有什么建议吗?你有两个问题 首先,在测试提示符是否为空字符串或null之前,通过parseInt运行提示符的返回值 那么您就不能区分null和“不是结果” 在开始测试之前,不要parseInt 在测试!=结
提示符是否为空字符串或null之前,通过parseInt
运行提示符的返回值
那么您就不能区分null和“不是结果”
- 在开始测试之前,不要
parseInt
- 在测试
!=结果
- 测试
userInput===parseInt(结果,10)
(始终使用基数和parseInt
)
从parseInt
返回的值永远不会严格等于null
。在调用parseInt
之前,请尝试测试输入
以下是一种有效的方法:
const
rand0To9=()=>Math.floor(Math.random()*9+1),
num1=rand0To9(),
num2=rand0To9(),
结果=num1*num2,
input=prompt(`What is${num1}*${num2}?`);
如果(输入!==null){
警报(`您是${parseInt(输入,10)=结果?“正确”:“错误”}!`);
}
当用户单击“取消”时,prompt()
确实返回null
,但通过parseInt()
传递时,此信息将丢失。您应该在尝试解析结果之前检查null
响应。非常感谢!另外,如果用户输入了两个或多个数字,包括正确答案,但仍显示为正确答案,我该如何处理这种情况?
var num1 = Math.floor(Math.random() * 9 + 1);
var num2 = Math.floor(Math.random() * 9 + 1);
var result = num1 * num2;
var userInput = parseInt(prompt('What is ' + num1 + ' * ' + num2 + ' ?'));
if (userInput === result){
alert('You are correct!');
} else if (userInput === '' || userInput !== result) {
alert('You are wrong!');
} else if (userInput === null) {
alert('Cancelled!');
}
if (userInput === result){
alert('You are correct!');
} else if (isNaN(userInput)) {
alert('Cancelled!');
} else if (userInput === '' || userInput !== result) {
alert('You are wrong!');
}