JavaScript中如何让函数获取另一函数返回值?石头剪刀布代码报错求助
石头剪刀布游戏问题排查
问题描述
近期开始学习编程,正在跟随Odin Project课程学习。目前尝试制作一款石头剪刀布游戏,但遇到了问题:编写了getComputerChoice函数用于让电脑随机返回Rock、Paper、Scissors三者之一;又编写了playRound函数,计划根据电脑的选择弹出对应提示,但始终弹出“Something went wrong”,说明playRound函数未正确获取到前者的返回值。代码如下:
// THIS FUNCTION DECIDES IF THE COMPUTER CHOOSES ROCK, PAPER OR SCISSOS function getComputerChoice () { var rand = Math.floor(Math.random() * 10); if (rand <= 3) { return "Rock" } else if (rand <= 6) { return "Paper" } else { return "Scissors" }} // I PUT THE COMPUTER CHOICE FUNCTION IN A CONST BOX const computerSelection = getComputerChoice(); // TESTING PLAYROUND FUNCTION function playRound(computerSelection) { if (computerSelection === "Paper") { alert("You lose! Paper beats Rock") } else if (computerSelection === "Rock") { alert("Draw") } else if (computerSelection === "Scissors") { alert("You win!") } else { alert("Something went wrong") } } function game() { for (let i = 0; i < 2 ; i++) { // your code here! playRound(); } } game();
问题原因及修复
- 未传递参数给
playRound函数:playRound定义时声明了computerSelection参数,但在game函数的循环里调用playRound()时没有传入任何值,导致函数内部的computerSelection为undefined,触发最后的else分支弹出错误提示。 - 电脑选择只初始化一次:当前代码里
computerSelection只在全局执行一次getComputerChoice(),循环两次都会使用同一个固定值,不符合每轮重新随机的需求。
修正后的代码
// 电脑随机选择函数 function getComputerChoice () { var rand = Math.floor(Math.random() * 10); if (rand <= 3) { return "Rock" } else if (rand <= 6) { return "Paper" } else { return "Scissors" } } // 单轮游戏函数 function playRound(computerSelection) { if (computerSelection === "Paper") { alert("You lose! Paper beats Rock") } else if (computerSelection === "Rock") { alert("Draw") } else if (computerSelection === "Scissors") { alert("You win!") } else { alert("Something went wrong") } } function game() { for (let i = 0; i < 2 ; i++) { // 每轮重新获取电脑选择并传入playRound const currentComputerChoice = getComputerChoice(); playRound(currentComputerChoice); } } game();
额外优化建议
- 可以给
playRound添加玩家选择的参数,让游戏逻辑更完整(比如接收玩家输入的Rock/Paper/Scissors后,再和电脑选择对比判断胜负)。 getComputerChoice里的随机数逻辑可以简化为Math.floor(Math.random() * 3),直接生成0-2的整数对应三个选项,这样三个选项的概率完全均匀(当前代码Rock和Paper各占40%,Scissors占30%)。
内容的提问来源于stack exchange,提问作者Antônio Hermano
相关产品推荐
相关产品推荐

