【问题标题】:How to distinguish between null and empty string in prompt window?如何区分提示窗口中的空字符串和空字符串?
【发布时间】:2023-04-10 23:43:01
【问题描述】:

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

  1. 如果用户输入了正确答案,则提示“您是正确的”。
  2. 如果用户输入错误答案或将其留空,则提示“您错了” 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!');
    }

即使我按下取消,警报也会显示“你错了”。我添加了取消警报仅作为示例。有什么建议吗?

【问题讨论】:

  • 虽然prompt() 确实在用户单击取消时返回null,但此信息在通过parseInt() 时会丢失。在尝试解析结果之前,您应该检查null 响应

标签: javascript prompt


【解决方案1】:

你有两个问题。

首先,您正在运行promptparseInt 的返回值您测试它是否为空字符串或null。

那么你没有区分 null 和“不是结果”。

  • 在开始测试之前不要parseInt
  • 测试null测试!== result
  • 测试userInput === parseInt(result, 10)(始终使用带有parseInt 的基数)

【讨论】:

  • 非常感谢!另外,如果用户输入两个或多个数字,包括正确答案,但它仍然说它是 wight 答案,我该如何处理?
【解决方案2】:
if (userInput === result){
    alert('You are correct!');
} else if (isNaN(userInput)) {
    alert('Cancelled!');
} else if (userInput === '' || userInput !== result) {
    alert('You are wrong!');
}

【讨论】:

    【解决方案3】:

    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" }!`);
    }

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2020-01-31
      • 2018-12-26
      • 1970-01-01
      • 2015-07-02
      • 2012-02-29
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多