Abd*_*dou 0 javascript if-statement
我当时正在做一个剪刀石头布挑战,当我需要设置一个决定获胜者的函数时,我觉得编写大量包含每个潜在情况的 if 语句根本不切实际。但在我进行了一次小搜索之后,我检查过的所有代码都使用了 if 语句。\xe2\x80\x99t 有没有更好的方法来做到这一点?
\n我将分享下面的代码:
\n //after the user clickes on scissor or paper or rock mymove function runs.\nfunction mymove(choice) {\n let humanchoice = choice.id \n //a while loop that runs till the computer choice is not the same as the user choice\n while (true){\n let pcnum = Math.random();\n console.log(pcnum);\n let pcchoie = 'paper';\n\n \n if(pcnum <= 0.33){\n pcchoie = "paper";\n \n } else if(pcnum <= 0.66){\n pcchoie = "scissor"; \n }else {\n pcchoie = "rock"; \n \n }\n console.log(pcchoie); \n\n \n if(humanchoice == pcchoie){ console.log ("lag");}\n else if(humanchoice != pcchoie){ break;}\n}\nRun Code Online (Sandbox Code Playgroud)\n}
\n现在我需要一种方法来设置规则,让计算机决定谁是赢家。
\n小智 5
您可以在对象中表示获胜者逻辑:
const beatenBy = {
"scissor": "paper",
"paper": "rock",
"rock": "scissor"
};
function decideWinner(humanChoice, pcChoice) {
if (humanChoice === pcChoice) {
return "draw";
}
else if beatenBy[humanChoice] === pcChoice {
return "human";
}
else {
return "pc";
}
}
Run Code Online (Sandbox Code Playgroud)