if语句-期望一个标识符,而不是else javascript

if statement - Expected an identifier and instead found else javascript

本文关键字:标识符 javascript else 一个 语句 期望 if      更新时间:2023-09-26
function compare(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"
        }
    }
}

错误是第二个else if语句。我是新的编程,所以我不知道什么是错的。错误声明它需要一个标识符,而不是其他

ifelse if……else块以else块结束

也就是说你只能用else块结束它。也就是说,else if不能在else之后

这样做:

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

如果从只有一个else If 块中返回,则不需要else部分。

function compare(choice1,choice2)
{
    if (choice1 === choice2)
    {
        return "The result is a tie!"
    }
    if (choice1 === "rock")
    {
        if (choice2 === "scissors") 
        {
        return "Rock wins"
        }
        return "Paper wins"
    }
    if (choice1 === "paper")
    {
        if (choice2 === "rock")
        {
        return "Paper wins"
        }
        return "Scissors wins"
    }
}

如果使用条件?:运算符,可以进一步减少:

function compare(choice1,choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!"
    }
    if (choice1 === "rock") {
        return choice2 === "scissors"? "Rock wins" : "Paper wins";
    }
    if (choice1 === "paper") {
        return choice2 === "rock"? "Paper wins" : "Scissors wins";
    }
    // You forgot this one
    if (choice1 === "scissors") {
        return choice2 === "rock"? "Rock wins" : "Scissors wins";
    }
}

当有许多二进制选择时,它更紧凑,更容易阅读。