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

关闭prompt弹窗触发TypeError及弹窗反复弹出问题的解决

解决getHumanChoice函数的null处理与循环问题

初始实现的问题

以下是最初实现的getHumanChoice函数:

function getHumanChoice() {
      
      let humanChoice = prompt('Choose rock, paper, or scissors:');
      
      if (humanChoice.toLowerCase() !== humanChoice){
        humanChoice = humanChoice.toLowerCase()
      }


      while (humanChoice !== 'rock' && humanChoice !== 'paper' && humanChoice !== 'scissors') {
        alert('Please enter a valid choice');
        humanChoice = prompt('Choose rock, paper, or scissors:');
      }
      
      return humanChoice
    }

当关闭prompt弹窗时,控制台会抛出TypeError——原因是对null执行了toLowerCase()方法。

第一次修改的问题

为处理null情况,我添加了if判断,虽然消除了错误,但prompt弹窗会持续弹出,控制台没有其他输出:

if(humanChoice === null){
        return null
} else {
        if (humanChoice.toLowerCase() !== humanChoice){
          humanChoice = humanChoice.toLowerCase()
        }


        while (humanChoice !== 'rock' && humanChoice !== 'paper' && humanChoice !== 'scissors') {
          alert('Please enter a valid choice');
          humanChoice = prompt('Choose rock, paper, or scissors:');
        }
        
        return humanChoice
}

修复后的代码

最终我通过以下代码解决了问题:

function getHumanChoice() {
      let humanChoice = prompt('Choose rock, paper, or scissors:');

      if (humanChoice === null) {
        return null;
      }

      humanChoice = humanChoice.toLowerCase();

      while (humanChoice !== 'rock' && humanChoice !== 'paper' && humanChoice !== 'scissors') {
        alert('Please enter a valid choice');
        humanChoice = prompt('Choose rock, paper, or scissors:');
      }

      return humanChoice;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:16