【问题标题】:Need help about booleans需要有关布尔值的帮助
【发布时间】: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


【解决方案1】:

if (!gameOver) 的缩写:

if (gameOver != true) {} // (gameOver is not true)

那么会发生什么: 当您单击按钮时,它会增加分数。 当分数与中奖分数相同时(p1Score === winningScore) 然后将gameOver设置为true,游戏结束。

他使用===,因为这意味着:p1Score must be exact the same aswinningScore。 这是因为 10 也是布尔值。所以这可能会产生一些不寻常的结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2014-12-26
    • 2013-08-12
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多