If else语句包含多个答案

If else statement with multiple answers

本文关键字:答案 包含多 语句 else If      更新时间:2023-09-26

我对此有点陌生,但我正在尝试编写一些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行。在您提供的jsFiddle中,else后面有一个额外的分号

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

您可以使用开关/案例:

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