如果else语句有多个答案

时间:2014-10-17 16:20:53

标签: javascript if-statement var

我对此有点新意,但我正在尝试编写一些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();
}

3 个答案:

答案 0 :(得分:0)

这是因为行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();
    }

答案 1 :(得分:0)

你得到了额外的分号&#39 ;;'在问题示例的第3行中。 在你提供的jsFiddle中,还有一个额外的分号

答案 2 :(得分:0)

您可以使用开关/案例:

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();
}