关闭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
相关产品推荐
相关产品推荐

