关闭时不断弹出提示

问题描述 投票:0回答:1
 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
    }


每当我尝试关闭提示时,我都会在控制台中收到类型错误。

由于错误是由执行 toLowerCase() 为 null 引起的,我尝试通过 if 语句解决它,我摆脱了错误,但提示不断出现,控制台不再执行任何操作。

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
}
javascript
1个回答
0
投票

我们需要打破循环,不是通过提示退出按钮,而是使用

breack;
。我们必须这样做,因为除非我们改变它,否则循环将永远存在。

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


      while (humanChoice !== 'rock' && humanChoice !== 'paper' && humanChoice !== 'scissors') {
        //We use going as continue is a keyword
        let going = window.prompt("Invailid answer. Would you like to continue? Y/N")
         //Seeing if user wants to continue, if not breack the loop.
        if(going == "Y"){
            alert('Please enter a valid choice');
            humanChoice = prompt('Choose rock, paper, or scissors:');
        } else { //If user types "N" for no breack and stop the loop.
            alert("Thanks for playing!")
          break;
        }
      }
      
      return humanChoice
    }

getHumanChoice() //Running code.
© www.soinside.com 2019 - 2024. All rights reserved.