【发布时间】:2018-08-25 15:11:06
【问题描述】:
我正在关注 Colt Steele 的 web 开发人员训练营,我正在参加 Score Keeper 练习,但我坚持一件事我还不太了解。因此,他将 gameOver 的变量设置为 false (var gameOver = false),并在 if 语句中使用了 if(!gameOver) { ....}。 !gameOver 实际上是什么意思?我知道这意味着在这种情况下不是假的,所以如果不是假的,那么运行代码?然后他在嵌套的 if 语句中将 gameOver 设置为 true,所以我知道当 gameOver 设置为 true 时,当 if 语句到达它时,整个条件变为 true?这意味着代码将不再运行,因为它达到“真”?有人可以更详细地向我解释一下吗?我对此感到困惑,特别是因为我第一次看到变量名称的否定被设置为任何布尔值,尤其是在 if 语句中。代码如下:
var p1Button = document.querySelector("#p1");
var p2Button = document.getElementById("p2");
var p1Display = document.querySelector("#p1Display");
var p2Display = document.querySelector("#p2Display");
var p1Score = 0;
var p2Score = 0;
var gameOver = false;
var winningScore = 5;
p1Button.addEventListener("click", function(){
if (!gameOver) {
p1Score++;
if (p1Score === winningScore) {
gameOver = true;
}
p1Display.textContent = p1Score;
}
});
p2Button.addEventListener("click", function(){
if (!gameOver) {
p2Score++;
if (p2Score === winningScore) {
gameOver = true;
}
p2Display.textContent = p2Score;
}
});
【问题讨论】:
-
!gameOver 是一个条件检查,大致相当于“这游戏还没有结束吗?”在您的代码的上下文中。当 bool 设置为 'true' 时,该条件的评估不再为真,这意味着条件括号内的代码不再执行。
标签: boolean