我想知道如何在两个 bool(boolean) 变量之间切换。这在第一次运行代码时可以正常运行,但是在第二次运行之后,输出将不正确。

输出第一次运行switchPlayer():

player1.isActive = false,
player2.isActive = true

输出第二次运行switchPlayer():
player1.isActive = true,
player2.isActive = true

以下是我编写的代码:
var Player = function(score, isActive){
  this.score = score;
  this.isActive = isActive;
}

Player.prototype.toggleIsActive = function(){
      if(this.isActive === false){
        this.isActive = true;
      } else{
        this.isActive = false;
      }
    }

function switchPlayer(){
  if(player1.isActive === true){
    player1.toggleIsActive();
    player2.toggleIsActive();
  } else{
    player1.isActive = true;
  }
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);

switchPlayer();
switchPlayer();

最佳答案

您可以像这样简化它:

Player.prototype.toggleIsActive = function(){
   this.isActive = !this.isActive;
}

function switchPlayer(){
    player1.toggleIsActive();
    player2.toggleIsActive();
}

ToggleIsActive应该与以前相反。还要注意,switchPlayer仅调用没有特定逻辑的切换。

关于javascript - 在 bool 变量之间切换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53214599/

10-14 14:35