剪刀石头布JavaScript游戏故障排查:结果不显示问题求助
问题排查与修复
- 核心错误:DOM元素ID拼写错误
你在获取结果显示元素时,把result拼写成了resut,导致resultDisplay为null,无法设置结果内容。
// 错误代码 const resultDisplay = document.getElementById('resut') // 修正后 const resultDisplay = document.getElementById('result')
- 可选优化建议
generateComputerChoice的条件判断改用switch语句,逻辑更清晰:
function generateComputerChoice(){ const randomNumber = Math.floor(Math.random() * possibleChoices.length) + 1 switch(randomNumber){ case 1: computerChoice = 'rock' break case 2: computerChoice = 'scissors' break case 3: computerChoice = 'paper' break } computerChoiceDisplay.innerHTML = computerChoice }getResult改用else if减少不必要的判断:
function getResult(){ if (computerChoice === userChoice){ result = 'its a draw!' } else if (computerChoice === 'rock' && userChoice === 'paper'){ result = 'you win!' } else if (computerChoice === 'rock' && userChoice === 'scissors'){ result = 'you lost!' } else if (computerChoice === 'paper' && userChoice === 'scissors'){ result = 'you win!' } else if (computerChoice === 'paper' && userChoice === 'rock'){ result = 'you lost!' } else if (computerChoice === 'scissors' && userChoice === 'rock'){ result = 'you win!' } else if (computerChoice === 'scissors' && userChoice === 'paper'){ result = 'you lost!' } resultDisplay.innerHTML = result }
内容的提问来源于stack exchange,提问作者Flavius Popa
相关产品推荐
相关产品推荐

