gpt4 book ai didi

javascript - JavaScript 中的石头、剪刀、布

转载 作者:行者123 更新时间:2023-11-28 13:36:32 24 4
gpt4 key购买 nike

我正在上 Codecademy 类(class)(找到 here ),但一直告诉我“当输入是纸和石头时,您的代码返回‘石头获胜’而不是‘纸获胜’”,为什么?应该是正确的。既然它在谈论“石头获胜”,那么它就在谈论石头与剪刀。那么,当“石头获胜”的唯一结果中甚至不涉及纸张时,为什么要说“而不是纸张获胜”呢?

var compare = function (choice1, choice2) {  

if (choice1 === choice2) {
return("The result is a tie!");
}

if (choice1 === "rock") {
if (choice2 === "scissors");
} else {
return ("rock wins");
}

if (choice1 === "paper") {
if (choice2 === "rock");
} else {
return ("paper wins");
}

if (choice1 === "paper") {
if (choice2 === "scissors");
} else {
return ("scissors wins");
}

};

最佳答案

看看你的第一个条件:

if (choice1 === "rock") {
if (choice2 === "scissors");
} else {
return ("rock wins");
}

因此,如果 choice1 很稳定,您可以输入 if block (它实际上不会返回任何内容,但因为在本例中 choice1 > 实际上是 "paper" 它进入 else block ,无条件返回 "rock win"。尝试将其重构为类似这个:

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

关于javascript - JavaScript 中的石头、剪刀、布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com