JavaScript控制台石头剪刀布游戏始终触发输入报错求助
JavaScript初学者控制台石头剪刀布项目故障排查
你的代码始终触发错误提示的根源是输入值格式和判断逻辑要求的格式不匹配,具体问题点如下:
- 输入格式化逻辑没有实际生效
你获取用户输入时调用了.toLowerCase()把输入统一转成了全小写格式(比如输入Rock会变成rock),虽然编写了caseInsensitive函数用来把小写字符串转回首字母大写的标准格式(转完是Rock),但你只是在控制台打印了这个函数的返回结果,没有把格式化后的值赋值给playerSelection变量。最终传入playRound函数的始终是全小写的输入值,和判断条件里写的首字母大写的Rock/Paper/Scissors完全不相等,所有胜负、平局的判断分支都不会命中,直接走到最后返回错误提示的else分支。 - 逻辑写法存在冗余
computerPlay函数依赖外部定义的randomInt全局变量,把随机数生成逻辑放到函数内部可以避免不必要的全局变量,代码结构更清晰。
修复后可正常运行的完整代码如下:
// 格式化用户输入为首字母大写的标准格式 function caseInsensitive(str) { return str.charAt(0).toUpperCase() + str.slice(1); } // 电脑随机出拳逻辑 function computerPlay() { const randomInt = Math.floor(Math.random() * 3); if (randomInt === 0) { return 'Rock'; } else if (randomInt === 1) { return 'Paper'; } else { return 'Scissors' } } // 单轮胜负判断逻辑 function playRound(playerSelection, computerSelection) { if (playerSelection == 'Rock' && computerSelection == 'Scissors') { return `You win! ${playerSelection} beats ${computerSelection}` } else if (playerSelection == 'Paper' && computerSelection == 'Rock') { return `You win! ${playerSelection} beats ${computerSelection}` } else if (playerSelection == 'Scissors' && computerSelection == 'Paper') { return `You win! ${playerSelection} beats ${computerSelection}` } else if (playerSelection == 'Scissors' && computerSelection == 'Rock') { return `You lose! ${computerSelection} beats ${playerSelection}` } else if (playerSelection == 'Rock' && computerSelection == 'Paper') { return `You lose! ${computerSelection} beats ${playerSelection}` } else if (playerSelection == 'Paper' && computerSelection == 'Scissors') { return `You lose! ${computerSelection} beats ${playerSelection}` } else if (playerSelection == computerSelection) { return `It's a tie, Refresh to play again!` } else { return `Error. Only enter Rock, Paper, or Scissors` } } // 主流程:获取输入、格式化、生成电脑出拳、执行判断打印结果 const rawInput = prompt('Rock, Paper, Scissors?').toLowerCase(); const playerSelection = caseInsensitive(rawInput); const computerSelection = computerPlay(); console.log('玩家出拳:', playerSelection) console.log('电脑出拳:', computerSelection) console.log(playRound(playerSelection, computerSelection));
内容的提问来源于stack exchange,提问作者jsb
相关产品推荐
相关产品推荐

