Javascript:意外的标记else

Javascript: Unexpected token else

本文关键字:else 意外 Javascript      更新时间:2023-09-26

我正在使用CodeAcademy,我正在制作一个石头、纸、剪刀的游戏。它一直说我有一个语法错误,原因是"意外的令牌else"。看看我的代码:

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!";
  }
  }
 }
}

您有一个if块,它看起来像这样:

       if (choice2 === "scissors") {
          ...
       } else {
          ...
       } else if (choice1 === "paper") {
          ...
       }

else if只能出现在else之前,而不能出现在之后。

使用一致的缩进将使这类问题更加清晰,以下是在http://jsbeautifier.org/

   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!";
               }
           }
       }
   }

这里再次对其进行格式化,使choice1 ===行都处于函数级别,这似乎使其更容易查看结构并减少嵌套。

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

您在return ("paper wins!");中使用了带有return语句的圆括号。请移除()

此外,在第一个else-if和第二个else-if之前对齐的括号数量错误。

如果使用花括号},请先关闭else,并从底部删除一个多余部分。这是错误的主要原因!

您似乎使用了错误数量的花括号。