在 switch 语句中使用
alert()
可以工作,但为什么它不能使用下面的代码在浏览器中显示结果?
JS文件:
do {
let playerMove = prompt('Please enter your move', 'e.g rock, paper or scissors');
let computerMove = ['rock', 'paper', 'scissors'];
switch (playerMove){
case 'rock':
document.querySelector('p').innerHTML= computerMove[Math.floor(Math.random()*3)] + ' vs your rock';
break;
case 'paper':
document.querySelector('p').innerHTML= computerMove[Math.floor(Math.random()*3)] + ' vs your paper';
break;
case 'scissors':
document.querySelector('p').innerHTML= computerMove[Math.floor(Math.random()*3)] + ' vs your scissors';
break;
default:
document.querySelector('p').innerHTML= 'You need to learn how to play Rock, Paper, Scissors';
}
} while (confirm('Wanna play again?'))
HTML 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Rock Paper Scissors</h2>
<p></p>
<script src ='main.js'></script>
</body>
</html>
问题是因为 JS 是单线程的。因此,该线程仍然停留在您的
while
循环中,无法重新绘制 UI。 alert()
暂时停止此循环并允许重新绘制。
改善此问题的最佳方法是删除
while
循环,并将逻辑放入一个函数中,如果玩家想继续玩另一个游戏,该函数会递归调用自身:
const playGame = () => {
let playerMove = prompt('Please enter your move', 'e.g rock, paper or scissors');
let computerMove = ['rock', 'paper', 'scissors'];
switch (playerMove) {
case 'rock':
document.querySelector('p').innerHTML = computerMove[Math.floor(Math.random() * 3)] + ' vs your rock';
break;
case 'paper':
document.querySelector('p').innerHTML = computerMove[Math.floor(Math.random() * 3)] + ' vs your paper';
break;
case 'scissors':
document.querySelector('p').innerHTML = computerMove[Math.floor(Math.random() * 3)] + ' vs your scissors';
break;
default:
document.querySelector('p').innerHTML = 'You need to learn how to play Rock, Paper, Scissors';
}
if (confirm('Wanna play again?'))
playGame();
}
playGame();
<h2>Rock Paper Scissors</h2>
<p></p>