Odin Project基础课石头剪刀布项目:playRound函数无限运行修复咨询
解决石头剪刀布playRound函数无法终止的问题
你的代码里有几个核心错误导致函数无法终止,直接修改就能解决,不需要完全重写,具体问题和修改方案如下:
原代码问题分析
function getComputerChoice(){ //create array of (rock, paper, scissors) const listOfWeapons = new Array ('Rock','Paper','Scissors'); //make computer choose randomly between the objects of the array let computerChoice = listOfWeapons[Math.floor(Math.random()*listOfWeapons.length)]; console.log(computerChoice) } getComputerChoice(); function playRound(playerSelection, computerSelection){ let getPlayerSelection = prompt('Choose your weapon!'); if (getComputerChoice == getPlayerSelection){ alert('It\'s a tie you both have choosen the same weapon') } for (getComputerChoice == 'Rock'; getPlayerSelection == 'Paper';){ alert('You won paper beats rock') } for (getComputerChoice == 'Rock'; getPlayerSelection == 'Scissors';){ alert('You lost rock beats scissors') } for (getComputerChoice == 'Paper'; getPlayerSelection == 'Scissors';){ alert('You won scissors beats paper') } for (getComputerChoice == 'Paper'; getPlayerSelection == 'Rock';){ alert('You lost paper beats rock') } for (getComputerChoice == 'Scissors'; getPlayerSelection == 'Rock';){ alert('You won rock beats paper') } for (getComputerChoice == 'Scissors'; getPlayerSelection == 'Paper';){ alert('You lost scissors beats paper') } } playRound();
- getComputerChoice函数无返回值:这个函数只打印电脑选择,没有返回结果,你直接拿函数名
getComputerChoice和玩家选择比较,完全不成立,根本拿不到电脑的实际选择。 - 错误使用for循环:你用for循环来判断胜负是完全错误的写法,for循环的语法是
for(初始化表达式; 条件表达式; 增量表达式),你写的循环没有终止条件(第三个参数为空),一旦条件满足,就会无限执行alert,这就是函数无法终止的直接原因。 - 参数冗余+逻辑错误:playRound定义了参数但没用到,而且胜负判断里有文案错误(比如电脑选Scissors玩家选Rock时,提示写成了"rock beats paper",实际应该是"rock beats scissors")。
修改后的代码
// 修改getComputerChoice,让它返回电脑的选择 function getComputerChoice(){ const listOfWeapons = ['Rock','Paper','Scissors']; return listOfWeapons[Math.floor(Math.random()*listOfWeapons.length)]; } function playRound(){ // 获取玩家选择并统一格式(避免大小写不匹配) const input = prompt('Choose your weapon!').trim(); const playerSelection = input.charAt(0).toUpperCase() + input.slice(1).toLowerCase(); // 获取电脑选择 const computerSelection = getComputerChoice(); // 用if-else if判断所有胜负情况,每个分支执行后自然结束函数 if (playerSelection === computerSelection){ alert(`It's a tie! You both chose ${playerSelection}`); } else if ( (computerSelection === 'Rock' && playerSelection === 'Paper') || (computerSelection === 'Paper' && playerSelection === 'Scissors') || (computerSelection === 'Scissors' && playerSelection === 'Rock') ){ alert(`You won! ${playerSelection} beats ${computerSelection}`); } else { alert(`You lost! ${computerSelection} beats ${playerSelection}`); } } // 调用函数 playRound();
修改说明
- 让
getComputerChoice返回电脑的选择,这样playRound里能拿到真实的电脑选择值。 - 去掉playRound的冗余参数,直接在函数内部获取玩家和电脑的选择。
- 对玩家输入做了格式化处理,不管输入大小写都能正确匹配(比如输入"rock"会转成"Rock")。
- 用
if-else if-else替代错误的for循环,每个条件分支执行alert后函数会自然终止,不会出现无限循环。 - 修正了胜负提示的文案错误,用模板字符串让提示更清晰。
内容的提问来源于stack exchange,提问作者Stefano D'Angelo
相关产品推荐
相关产品推荐

