岩纸剪刀游戏错误,Javascript

时间:2015-10-13 23:52:46

标签: javascript debugging syntax error-handling syntax-error

我不断从控制台收到此错误:

  

SyntaxError:期望表达式,得到关键字'否则'否则如果(选择2   ===" paper"){

这是我的代码

var user = prompt("Rock, Paper, Scissors?");
var computer = Math.random();
if (computer < 0.34) {
    computer = "rock";
} else if (computer <= 0.67) {
    computer = "paper";
} else {
    computer = "scissors";
} console.log("computer: " + computer);

var compare = function (choice1, choice2) {

    if (choice1 === choice2) {
        return "Tie";
    }
else if (choice1 === "rock") {
    return "Rock wins";
}
else {
    return "paper wins";
}

}
else if (choice2 === "paper") {
    if (choice2 === "rock") {
        return "paper wins";
    }
    else {
        return "scissors win";
    }
}
}
compare(user, computer);

1 个答案:

答案 0 :(得分:1)

好。

您在第25行左右结束比较功能,然后启动另一个else。所以这不好,但它只是一个重复的大括号,所以当删除它时我们仍然得到错误。这是因为您在else if后调用else

当我们将else移动到else if下并移除重复的大括号时,我们会得到一些实际运行的代码

var user = prompt("Rock, Paper, Scissors?");
var computer = Math.random();
if (computer < 0.34) {
    computer = "rock";
} else if (computer <= 0.67) {
    computer = "paper";
} else {
    computer = "scissors";
}
console.log("computer: " + computer);

var compare = function(choice1, choice2) {

    if (choice1 === choice2) {
        return "Tie";
    } else if (choice1 === "rock") {
        return "Rock wins";
    } else if (choice2 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        } else {
            return "scissors win";
        }
    } else {
        return "paper wins";
    } 
}
compare(user, computer);

希望这会有所帮助。当你使用工具来美化你的代码时,它也更容易调试(参见额外的花括号),我使用 - &gt; http://jsbeautifier.org/