You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript 猜硬币正反按钮程序输出错误且胜负计数器不显示问题

问题点
  • 永远返回incorrect的原因有两个:
    1. 你用数字类型的flip(取值为0或1)直接和字符串类型的'heads'/'tails'做相等判断,二者类型不匹配永远返回false
    2. flip是页面加载时生成的固定值,不是每次点击按钮重新抛硬币生成的新结果,就算判断逻辑改对也只会用第一次的抛硬币结果
  • 计数器不展示的原因有三个:
    1. 两个按钮没有添加id="heads"和id="tails"属性,JS中getElementById拿不到元素,事件绑定失效
    2. 展示统计的字符串用了单引号包裹,不是JS模板字符串要求的反引号,导致变量不会被解析,只会输出原始的${win}文本
    3. 你先给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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:45:03