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

猜色游戏尝试次数无法递增求助:始终显示第1次

问题原因及解决办法

核心问题有两个:

  1. numTries 每次都会被重置:你把numTries声明在checkGuess函数内部,每次调用这个函数时,numTries都会被重新赋值为0。不管之前猜了多少次,只要触发函数,计数就回到0,加1后自然永远显示1。
  2. 循环根本没生效:你的do-while循环里,第一次执行就调用了return correct,直接跳出函数,循环体只会执行一次,完全起不到重复尝试的作用。

解决步骤:

第一步:把计数变量移到函数外部

把numTries的声明放在函数外面,这样每次调用函数时不会重置计数:

let numTries = 0; // 移到函数外部,保存累计次数

function checkGuess(guess, target) {
    let correct = false;
        
    if (!COLORS_ARRAY.includes(guess))  {
        numTries ++;
        alert('你必须选择列表中的颜色之一。点击确定重试。');
    } else if (guess < target) {
        numTries ++;
        alert('错误。这是你的第 ' + numTries + ' 次尝试。\n\n字母顺序过高');
    } else if (guess > target) {
        numTries ++;
        alert('错误。这是你的第 ' + numTries + ' 次尝试。\n\n字母顺序过低');
    } else {
        correct = true;
        document.body.style.background = guess;
        numTries = 0; // 猜对后重置计数,方便下一轮游戏
    } 
    return correct;
}

第二步:移除无效的do-while循环

原函数里的do-while循环完全没用,因为return语句直接终止了函数。你应该让外部逻辑(比如用户点击按钮的事件)来重复调用checkGuess,毕竟用户的每一次猜测都是独立的交互操作,函数只需要处理单次猜测即可。

额外提示(避免全局变量污染):

如果不想用全局变量,可以用闭包封装计数变量:

const createGuessChecker = () => {
    let numTries = 0;
    return (guess, target) => {
        let correct = false;
        if (!COLORS_ARRAY.includes(guess))  {
            numTries ++;
            alert('你必须选择列表中的颜色之一。点击确定重试。');
        } else if (guess < target) {
            numTries ++;
            alert('错误。这是你的第 ' + numTries + ' 次尝试。\n\n字母顺序过高');
        } else if (guess > target) {
            numTries ++;
            alert('错误。这是你的第 ' + numTries + ' 次尝试。\n\n字母顺序过低');
        } else {
            correct = true;
            document.body.style.background = guess;
            numTries = 0;
        } 
        return correct;
    };
};

// 使用时创建检查函数
const checkGuess = createGuessChecker();

内容的提问来源于stack exchange,提问作者Trevon22

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:50:29