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

TOP石头剪刀布项目Bug求助:弹出undefined及TypeError问题

问题分析与解决方案

问题根源

报错Uncaught TypeError: Cannot read properties of null (reading 'toLowerCase')是因为用户关闭或取消prompt弹窗时,prompt()会返回null,此时直接对null调用.toLowerCase()就会触发类型错误。而计分板前弹出的undefined,是因为这个错误中断了后续正常逻辑,导致本该正确赋值的变量未被初始化,最终输出了undefined。

解决方案

核心是先处理prompt()返回null或空输入的边界情况,再执行后续逻辑,不能直接对可能为null的结果调用字符串方法。

代码修改示例

假设你原本的game函数逻辑类似这样:

function game() {
  let playerSelection = prompt("请选择:石头/剪刀/布");
  playerSelection = playerSelection.toLowerCase(); // 这里触发报错
  // 后续游戏逻辑与计分板代码
}

修改为:

function game() {
  let playerSelection = prompt("请选择:石头/剪刀/布");
  
  // 处理用户取消输入或空输入的情况
  if (!playerSelection) {
    alert("已取消游戏");
    return; // 终止函数,避免后续报错
  }

  // 先去除首尾空格再转小写
  playerSelection = playerSelection.trim().toLowerCase();

  // 额外验证输入合法性(可选但推荐)
  const validChoices = ["石头", "剪刀", "布"];
  if (!validChoices.includes(playerSelection)) {
    alert("请输入有效选项:石头、剪刀、布");
    game(); // 重新调用游戏,让用户正确输入
    return;
  }

  // 后续正常执行游戏逻辑与计分板代码
}

为什么之前修改prompt().toLowerCase()无效?

如果你的写法是let playerSelection = prompt().toLowerCase(),那当用户取消prompt时,prompt()返回null,链式调用.toLowerCase()直接触发报错,根本没机会处理null的情况。必须先获取prompt()的结果,判断是否为null或空值后,再执行字符串转换操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:08