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

JavaScript猜数字游戏故障:非首次猜中时页面无限加载

问题排查:猜数字游戏后续猜中时无限加载的原因及修复

核心问题

你代码里的隐性类型不匹配导致了无限循环:

  • 首次猜数时你用parseInt()把输入转成了数字,但后续的prompt直接将用户输入赋值给guess,此时guess是字符串类型
  • 而targetNum是数字类型,字符串和数字用!==比较永远不相等(比如"5" !== 5),循环会持续运行,导致页面假死

修复方案

每次获取用户输入后都用parseInt()转成数字,确保guess始终是数字类型:

let maximum = parseInt(prompt("Enter a maximum number"));
const targetNum = Math.floor((Math.random() * maximum) + 1);

while (!maximum) {
  maximum = parseInt(prompt("Enter a valid number"))
}
console.log(targetNum);

let guess = parseInt(prompt("Enter your first guess"));
let attempts = 1;
while (guess !== targetNum) {
  console.log(new Date());
  attempts++;
  if (guess > targetNum) {
    guess = parseInt(prompt("TOO HIGH! Try again"))
  } else if (guess < targetNum) {
    guess = parseInt(prompt("TOO LOW! Try again"))
  }
  // 处理用户取消输入的情况,避免循环卡死
  if (isNaN(guess)) {
    alert("输入无效,游戏结束");
    break;
  }
}
if (guess === targetNum) {
  console.log(`You got it! it took you ${attempts} attempts`);
}

额外优化建议

  • 给parseInt加上第二个参数指定十进制解析:parseInt(input, 10),避免非十进制的意外解析
  • 增加输入有效性判断,防止用户输入非数字内容导致逻辑异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:25:47