简体   繁体   English

意外的其他标记,if语句后不是分号

[英]Unexpected token else, not a semicolon after if statement

Trying to write a rock paper scissors game, using codecademy to learn. 尝试编写一个石头剪刀布游戏,使用codecademy学习。 I've seen a lot of people talking about this error and it being related to using a semicolon after an if statement but I don't know if I'm completely missing something or it's something different. 我见过很多人在谈论此错误,它与在if语句后使用分号有关,但我不知道我是否完全遗漏了某些内容或有所不同。 Here's the code, it's a little weird to understand (and least to me), but hopefully you'll see what I didn't 这是代码,理解起来有点奇怪(至少对我来说是如此),但是希望您能看到我没有的东西

var compare = function(choice1, choice2) {
    if(choice1 === choice2) {
        return "The result is a tie!";
    }
    else if(choice1 === "rock") {
        if(choice2 === "scissors") {
            return "rock wins";
        }
        else {
            return "paper wins";
        }
    else if(choice1 === "paper") {  
        if (choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }
    }
};
}

Try removing the } at the end of your code (line 21) and place it on line 12 instead. 尝试删除代码末尾的} (第21行),然后将其放在第12行。

Fixed code: 固定代码:

var compare = function(choice1, choice2) {
    if(choice1 === choice2) {
        return "The result is a tie!";
    }
    else if(choice1 === "rock") {
        if(choice2 === "scissors") {
            return "rock wins";
        }
        else {
            return "paper wins";
        }
    }
    else if(choice1 === "paper") {  
        if (choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }
    }
};

You're missing a closing brace } before your second else if statement, and you have an extra one near the end of your code. 您在第二个else if语句之前缺少了右括号} ,并且在代码末尾还有一个多余的括号。

Fixed code : 固定代码:

var compare = function(choice1, choice2) {
    if(choice1 === choice2) {
        return "The result is a tie!";
    }
    else if(choice1 === "rock") {
        if(choice2 === "scissors") {
            return "rock wins";
        }
        else {
            return "paper wins";
        }
    }
    else if(choice1 === "paper") {  
        if (choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }
    }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM