JavaScript版石头剪刀布功能异常问题排查
石头剪刀布项目问题修复方案
核心Bug修复
1. 电脑无法生成「剪刀」选项
你的genCompChoice函数中,当随机数num === 2时,错误使用了比较运算符===而非赋值运算符=,导致compChoice永远不会被设置为scissors,这直接造成玩家选石头/剪刀时,只会出现两种结果。
修复代码:
function genCompChoice() { let num = Math.floor(Math.random() * 3) if (num === 0) { compChoice = 'rock' } if (num === 1) { compChoice = 'paper' } if (num === 2) { compChoice = 'scissors' // 把===改为= } }
2. 「Paper赢Rock」的结果未正确赋值
getResult函数中,处理paper击败rock的分支时,同样误用了===,导致该场景下结果为空,进一步引发显示异常。
修复代码:
if (userChoice === 'paper' && compChoice === 'rock') { result = 'Paper beats rock. You win.' // 把===改为= }
稳定性与性能优化
1. 统一点击事件处理
原代码为每个武器单独绑定点击事件,可改用事件委托简化逻辑,避免重复代码同时提升稳定性:
document.getElementById('weaponsgrid').addEventListener('click', (e) => { // 找到点击的武器容器 const weapon = e.target.closest('.weapons'); if (!weapon) return; // 点击非武器区域则退出 userChoice = weapon.id; genCompChoice(); getResult(); });
2. 优化结果判断逻辑
原代码用大量if分支判断结果,可改用对象映射简化,让代码更易维护:
function getResult() { const resultRules = { 'rock-rock': 'Draw. You both suck.', 'rock-paper': 'Paper beats rock. You lose.', 'rock-scissors': 'Rock beats scissors. You win.', 'paper-rock': 'Paper beats rock. You win.', 'paper-paper': 'Draw. You both suck.', 'paper-scissors': 'Scissors beats paper patrick. You lost nerd.', 'scissors-rock': 'Rock beats scissors. Are you even trying?', 'scissors-paper': 'Scissors beats paper. You win.', 'scissors-scissors': 'Draw. You both suck.' }; result = resultRules[`${userChoice}-${compChoice}`]; resultDisplay.textContent = result; // 用textContent替代innerHTML更安全 }
3. 变量初始化与全局污染优化
可将全局变量改为函数内局部变量或封装成模块,减少全局污染引发的潜在bug:
// 示例:封装为局部变量 function handleWeaponClick(weaponId) { const userChoice = weaponId; const compChoice = genCompChoice(); const result = getResult(userChoice, compChoice); resultDisplay.textContent = result; } // 对应的genCompChoice改为返回值形式 function genCompChoice() { const num = Math.floor(Math.random() * 3); if (num === 0) return 'rock'; if (num === 1) return 'paper'; return 'scissors'; }
内容的提问来源于stack exchange,提问作者Duskope
相关产品推荐
相关产品推荐

