如何区分提示window中的null和空字符串?

How to distinguish between null and empty string in prompt window?

我必须检查(提示 window 是强制性的)用户是否在这些条件下输入了正确的答案:

  1. 如果用户输入了正确答案,提醒 'you are correct'。
  2. 如果用户输入错误答案或留空,提醒 'you are wrong' 3 如果用户按下取消按钮,什么也不会发生。
    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!');
    }

即使我按取消,警报也会显示 'you are wrong'。我添加取消警报只是为了举例。有什么建议吗?

你有两个问题。

首先你是运行prompt的return值通过parseInt之前你测试看是否是空字符串或 null。

那你没有区分null和"not the result"。

  • 在开始测试之前不要parseInt
  • 测试 null 测试 !== result 之前
  • 测试 userInput === parseInt(result, 10)(始终使用带有 parseInt 的基数)
if (userInput === result){
    alert('You are correct!');
} else if (isNaN(userInput)) {
    alert('Cancelled!');
} else if (userInput === '' || userInput !== result) {
    alert('You are wrong!');
}

parseInt 返回的值永远不会严格等于 null。在调用 parseInt.

之前尝试测试 input

这是一种可行的方法:

const
  rand0To9 = () => Math.floor(Math.random() * 9 + 1),
  num1 = rand0To9(),
  num2 = rand0To9(),
  result = num1 * num2,
  input = prompt(`What is ${num1} * ${num2}?`);

if (input !== null){
  alert(`You are ${ parseInt(input, 10) == result ? "correct" : "wrong" }!`);
}