看看你的第一个条件:
if (choice1 === "rock") {
if (choice2 === "scissors");
} else {
return ("rock wins");
}
所以,如果choice1
是摇滚,你进入if
- 块(这实际上并不返回任何东西,但因为在这种情况下choice1
实际上是"paper"
它会进入else
- 块,无条件返回"rock wins"
。尝试重构它是这样的:
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");
}
}
if (choice1 === "paper") {
if (choice2 === "scissors") {
return ("scissors wins");
} else {
return ("rock wins");
}
}
但是,嘿,让我们看看吧。尝试把你的选择到一个数组:
var choices = ["rock", "paper", "scissors"];
现在,请注意在右边的项目总是击败项目向左(如果我们认为阵列环绕)。我们如何使用它来简化代码?那么我们就可以比较每个选择的指标,同时注意处理剪刀石头对比的边缘情况:
var x = choices.indexOf(choice1),
y = choices.indexOf(choice2);
if (x === y) {
return("The result is a tie!");
} else if (x > y) {
if (x == 3 && y == 0) {
return choice2 + " wins";
} else {
return choice1 + " wins";
}
} else {
return choice2 + " wins";
}
但是我们可以使用remainder operator(%
)这里更容易地处理的边缘情况:
var choices = ["rock", "paper", "scissors"];
var compare = function (choice1, choice2) {
var x = choices.indexOf(choice1),
y = choices.indexOf(choice2);
if (x === y) {
return("The result is a tie!");
}
return (((x - y) % 3) > 0 ? choice1 : choice2) + " wins";
}
'if(choice1 ===“paper”){if(choice2 ===“rock”);如果两个条件都是真的,或者你正在试图用这种方法做什么,那么你是不是该如何测试。阅读逻辑运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators –
也许这会帮助 - http://bit.ly/19NPQLh –
问题后分号'if'语句。 – elclanrs