Javascript:意外的标记else
Javascript: Unexpected token else
我正在使用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,并从底部删除一个多余部分。这是错误的主要原因!
您似乎使用了错误数量的花括号。
相关文章:
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 正在尝试使用if和else添加类,但无法正常工作
- 铬:“;未捕获的语法错误:意外的标记:"
- Javascript未捕获语法错误意外的标识符错误
- 在一个函数中,我有一个未捕获的语法错误:意外的标记else
- SyntaxError:意外的标记else(我在代码中找不到错误)
- 意外的“else”和函数未运行
- 未捕获的语法错误:if/else上的意外标识符
- PHP 中意外的 else 语句
- Codecademy语法错误意外的标记else
- "意外标记else"在美元each()
- Javascript:意外的标记else
- If/else If/else错误-意外标识符
- 未捕获的SyntaxError:
- Javascript控制台返回意外的令牌else
- 只需要验证--未捕获的语法错误:意外的标记else
- Codecademy“;SyntaxError:意外的标记else"
- 未捕获的SyntaxError:意外的令牌else,卡住了
- 未捕获的SyntaxError:意外的令牌else,完全被难住了