JavaScript 猜硬币正反按钮程序输出错误且胜负计数器不显示问题
问题点
- 永远返回incorrect的原因有两个:
- 你用数字类型的
flip(取值为0或1)直接和字符串类型的'heads'/'tails'做相等判断,二者类型不匹配永远返回false flip是页面加载时生成的固定值,不是每次点击按钮重新抛硬币生成的新结果,就算判断逻辑改对也只会用第一次的抛硬币结果
- 你用数字类型的
- 计数器不展示的原因有三个:
- 两个按钮没有添加
id="heads"和id="tails"属性,JS中getElementById拿不到元素,事件绑定失效 - 展示统计的字符串用了单引号包裹,不是JS模板字符串要求的反引号,导致变量不会被解析,只会输出原始的
${win}文本 - 你先给
output.textContent赋值了猜测结果,马上又用统计值覆盖了该属性,猜测结果直接被顶掉看不到
- 两个按钮没有添加
- 额外冗余问题:按钮同时通过
onclick属性和addEventListener绑定了两次点击事件,每次点击会触发两次处理函数,导致胜负统计计数翻倍
修复后的代码
HTML代码
<!DOCTYPE html> <html> <head> <title>Project 2</title> </head> <body> <script src = "jasc.js" defer></script> <p>Guess heads or tails:</p> <form name = 'headsTails'> <!-- 添加id属性,去掉冗余的onclick属性 --> <input type ='button' value = 'heads' id="heads" /> <input type ='button' value = 'tails' id="tails" /> </form> <div id = 'output'></div> </body> </html>
JS代码
const coin = ['heads', 'tails']; const form = document.forms.headsTails; const output = document.getElementById('output'); const heads = document.getElementById('heads'); heads.addEventListener('click', headsChoice); const tails = document.getElementById('tails'); tails.addEventListener('click', tailsChoice); let win = 0; let loss = 0; function headsChoice(e){ // 每次点击重新抛硬币生成新结果 const flip = Math.floor(Math.random() * coin.length); let tip = ''; // 拿抛硬币的结果值和选择比较,不是拿索引和字符串比 if (coin[flip] == coin[0]) { tip = 'You guessed heads, you were correct!'; win++; } else { tip = 'You guessed heads, you were incorrect.'; loss++; } // 用反引号包裹模板字符串,拼接结果和统计信息 output.textContent = `${tip}\nWins: ${win} || Losses: ${loss}`; } function tailsChoice(e){ const flip = Math.floor(Math.random() * coin.length); let tip = ''; if (coin[flip] == coin[1]) { tip = 'You guessed tails, you were correct!'; win++; } else { tip = 'You guessed tails, you were incorrect.'; loss++; } output.textContent = `${tip}\nWins: ${win} || Losses: ${loss}`; }
内容的提问来源于stack exchange,提问作者user11495912
相关产品推荐
相关产品推荐

