【问题标题】:If else statement with multiple answers带有多个答案的 if else 语句
【发布时间】:2014-12-13 07:00:01
【问题描述】:

我对此有点陌生,但我正在尝试编写一些 javascript 代码并且遇到了一些麻烦。

我有以下代码,并反复检查,找不到问题。我已经通过 jsfiddle 运行它,但我无法弄清楚我哪里出错了。

var question = prompt('Who shot Abraham Lincoln?');
if (question == 'john wilkes booth' || question == 'John Booth' || question == 'John Wilkes Booth') {
    alert("That\'s Right!");
    window.location.href = 'q2.html';
} else {
    alert('Sorry, that\'s not right.');
    alert('Please try again');
    history.refresh();
}

【问题讨论】:

  • 从 if 语句 'John Wilkes Booth' 中删除分号);
  • @Prabhu 您应该将其列为答案,以便他将其标记为已回答。
  • 可能想在比较喜欢之前将答案转换为.toLowerCase()。无需在 " 中转义 ' 并调用 var answer!
  • 就像@Prabhu 说的删除你的分号..在你的小提琴中你也有分号......
  • 谢谢,这似乎有效!我知道这可能只是一个小错误。

标签: javascript if-statement var


【解决方案1】:

您可以使用开关/外壳:

var question = prompt('Who shot Abraham Lincoln?');
switch (question) {
    case 'john wilkes booth':
    case 'John Booth':
    case 'John Wilkes Booth':
            alert("That\'s Right!"); window.location.href = 'q2.html'; break;
    default:
            alert("Sorry, that\'s not right.");
            alert('Please try again');
            history.refresh();
    break;
}

或者更好,我认为:

var question = prompt('Who shot Abraham Lincoln?');
if (new RegExp("john( wilkes)? booth", "gi").test(question))
{
    alert("That\'s Right!"); window.location.href = 'q2.html';
}
else 
{
    alert("Sorry, that\'s not right.");
    alert('Please try again');
    history.refresh();
}

【讨论】:

    【解决方案2】:

    你有多余的分号';'在您的问题示例的第 3 行。 在您提供的 jsFiddle 中,在 else 之后有一个额外的分号

    【讨论】:

      【解决方案3】:

      这是因为 35 行中有分号,这将起作用:

          var question = prompt('Who shot Abraham Lincoln?');
          if (question == 'john wilkes booth' || question == 'John Booth' || question ==
              'John Wilkes Booth') {
              alert("That\'s Right!"); window.location.href = 'q2.html';
          } else 
          {
              alert("Sorry, that\'s not right.");
              alert('Please try again');
              history.refresh();
          }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        相关资源
        最近更新 更多