You need to enable JavaScript to run this app. JavaScript猜数字游戏调用updateScore()无法累计得分问题求助
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript猜数字游戏调用updateScore()无法累计得分问题求助

问题原因

  1. 你当前的得分变量humanScore、computerScore本身是全局声明支持累加的,无法累加的核心原因大概率是你每次调用updateScore前都会重复执行最开头的变量初始化代码,导致得分每次被重置为0,没有保留上一轮的结果。
  2. 现存的代码逻辑问题:compareGuesses函数内的用户、电脑猜测值是硬编码的固定常量,无法适配实际游戏中每轮猜测值动态变化的需求,也可能导致你误以为得分没有更新。
  3. 小瑕疵:updateScore的case false分支缺少返回值(不影响得分更新但不符合逻辑一致性),human变量拼写错误成humun,后续维护容易出错。

修复后可正常累加得分的代码

// 初始化代码仅在游戏启动时执行一次,不要放在每轮调用的逻辑中
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// 生成0-9的随机目标数
const generateTarget = () => {
  return Math.floor(Math.random() * 10);
};

// 猜测值改为动态入参,不要写死
const compareGuesses = (humanGuess, computerGuess) => {
  const secretTargetNumber = generateTarget();
  const humanDiff = Math.abs(humanGuess - secretTargetNumber);
  const computerDiff = Math.abs(computerGuess - secretTargetNumber);
  // 平票也算人类赢,直接返回布尔值即可无需if判断
  return humanDiff <= computerDiff;
};

const updateScore = (humanGuess, computerGuess) => {
  const isHumanWin = compareGuesses(humanGuess, computerGuess);
  isHumanWin ? humanScore += 1 : computerScore += 1;
};

// 测试:模拟三轮游戏,得分会正常累加
updateScore(3, 5);
updateScore(7, 2);
updateScore(1, 8);
console.log('人类最终得分:', humanScore);
console.log('电脑最终得分:', computerScore);

可选:持久化存储得分(刷新页面不丢失)

如果需要刷新页面后得分依然保留,可以把得分存在浏览器本地存储中,修改初始化和更新逻辑即可:

// 初始化时从本地存储读取,没有历史得分则默认设为0
let humanScore = Number(localStorage.getItem('humanScore')) || 0;
let computerScore = Number(localStorage.getItem('computerScore')) || 0;

const updateScore = (humanGuess, computerGuess) => {
  const isHumanWin = compareGuesses(humanGuess, computerGuess);
  if (isHumanWin) {
    humanScore += 1;
    localStorage.setItem('humanScore', humanScore);
  } else {
    computerScore += 1;
    localStorage.setItem('computerScore', computerScore);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:36:08