JavaScript石头剪刀布游戏alert()函数无响应问题求助
问题修复方案
核心错误分析与解决
常量无法修改导致代码中断
你用const声明了Humanity和AI变量,const定义的是只读常量,无法通过+=操作修改数值。代码执行到修改常量的步骤时会抛出错误,后续的alert语句根本不会执行。只需将const替换为let,让变量可修改:let Humanity = 0; let AI = 0;玩家输入未正确转小写
原代码中''.toLowerCase()是对空字符串做转小写处理,并没有作用在prompt的返回值上。如果玩家输入大写或混合大小写的内容(比如Rock),会和判断条件里的小写字符串不匹配,导致所有条件都不触发。正确的写法是把prompt获取到的输入转成小写:let playerDecision = prompt('Make your decision!')?.toLowerCase();这里的
?.是可选链操作符,用来处理用户点击取消按钮时prompt返回null的情况,避免出现类型错误。
可选优化:添加平局处理
原代码没有处理玩家和AI选择相同的情况,此时不会弹出任何提示。可以在所有条件最后添加else分支:
} else { alert('平局!'); }
修改后的完整代码
let Humanity = 0; let AI = 0; // 创建随机电脑选择函数 function getComputerChoice() { const choices = ['rock', 'paper', 'scissors']; const randomChoice = Math.floor(Math.random() * choices.length); const decision = choices[randomChoice]; return decision; } // 进行一轮游戏 function round() { let computerChoice = getComputerChoice(); let playerDecision = prompt('Make your decision!')?.toLowerCase(); if (playerDecision === 'rock' && computerChoice === 'scissors') { Humanity += 1; alert('Humanity Wins'); } else if (playerDecision === 'scissors' && computerChoice === 'paper') { Humanity +=1; alert('Humanity Wins'); } else if (playerDecision === 'paper' && computerChoice === 'rock') { Humanity += 1; alert('Humanity Wins'); } else if (playerDecision === 'rock' && computerChoice === 'paper') { AI += 1; alert('AI Wins'); } else if (playerDecision === 'scissors' && computerChoice === 'rock') { AI += 1; alert('AI Wins'); } else if (playerDecision === 'paper' && computerChoice === 'scissors') { AI += 1; alert('AI Wins'); } else { alert('平局!'); } } round();
内容的提问来源于stack exchange,提问作者Pete1230z
相关产品推荐
相关产品推荐

