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"
}
}
}
错误是第二个if语句。我是编程新手,所以我不知道出了什么问题。该错误表明它期望一个标识符,而不是
答案 0 :(得分:0)
if
... else 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"
}
}
答案 1 :(得分:0)
如果从 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";
}
}
当有许多二元选择时,哪个更紧凑,更容易阅读。