JS石头剪刀布游戏末尾函数无法执行、内部变量不可调用问题
问题诊断
你的playGam函数执行异常是多处代码逻辑错误共同导致的:
getComputerChoice函数声明时要求传入参数any作为随机数计算的乘数,但你在playGam内调用该函数时没有传参,运行时any值为undefined,Math.random() * undefined计算结果为NaN,无法拿到有效的电脑出拳值。- 你将电脑出拳值和字符串映射的
switch逻辑写在了全局作用域,页面加载时就会单独执行,完全没有和getComputerChoice函数绑定。getComputerChoice本身仅会返回0-2的数字,和getUserChoice返回的rock/paper/scissors字符串格式不统一,后续胜负判断的全等比对永远无法命中。 determineWinner函数缺失用户出paper的判断分支,只要用户出布,函数就会返回undefined,无法输出正确胜负结果。- 额外笔误:
playGam函数名少写了末尾的e,虽然不影响运行,但不符合常规命名语义。
修复后完整代码
const getUserChoice = userInput => { userInput = userInput.toLowerCase(); if (userInput == "rock" || userInput == "paper" || userInput == "scissors") { return userInput; } else { console.log('Enter a valid option') }; }; function getComputerChoice(max = 3) { const randomNum = Math.floor(Math.random() * max) switch (randomNum) { case 0: return 'rock'; case 1: return 'paper'; case 2: return 'scissors'; default: console.log('Select a valid option') } } function determineWinner(userChoice, computerChoice) { if (userChoice === computerChoice) { return 'The game was a tie' } if (userChoice === 'rock') { if (computerChoice === 'paper') { return 'The computer won!' } else { return 'You won' } } if (userChoice === 'scissors') { if (computerChoice === 'rock') { return 'Computer won!' } else { return 'You won!' } } if (userChoice === 'paper') { if (computerChoice === 'scissors') { return 'Computer won!' } else { return 'You won!' } } } const playGame = () => { const userChoice = getUserChoice('scissors'); const computerChoice = getComputerChoice(); console.log('You threw: ' + userChoice); console.log('The computer threw: ' + computerChoice); console.log(determineWinner(userChoice, computerChoice)); } playGame();
修改说明
- 给
getComputerChoice的参数添加默认值3,调用时不传参也能正常生成0-2的随机数,不会返回NaN。 - 将原本全局执行的
switch逻辑移入getComputerChoice函数内部,让函数直接返回和用户出拳格式一致的字符串,保证后续胜负判断的全等比对可以正常执行。 - 补全
determineWinner中用户出paper的胜负判断分支,覆盖所有出拳场景,避免返回undefined。 - 修正函数名拼写笔误为
playGame,保持语义清晰。
内容的提问来源于stack exchange,提问作者Angel Arias
相关产品推荐
相关产品推荐

