在布尔变量之间切换

时间:2018-11-08 19:10:43

标签: javascript

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

第一次运行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();

3 个答案:

答案 0 :(得分:8)

您可以这样简化它:

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

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

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

答案 1 :(得分:1)

您可以通过从if/else实现中删除switchPlayer()来实现:

function switchPlayer(){

  player1.toggleIsActive();
  player2.toggleIsActive();

}

另外,考虑像这样简化toggleIsActive()原型上的Player方法:

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

这是一个完整的例子:

var Player = function(score, isActive){
  this.score = score;
  this.isActive = isActive;
}

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

function switchPlayer(){

  player1.toggleIsActive();
  player2.toggleIsActive();
  
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);

console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')

switchPlayer();

console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')

switchPlayer();

console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')

答案 2 :(得分:1)

let player1 = {};
let player2 = {};

player1.isActive = false;
player2.isActive = true;

function toggle () {
  player1.isActive = !player1.isActive;
  player2.isActive = !player2.isActive;
  
  console.log('player1', player1.isActive, 'player2', player2.isActive);
}
<button onclick="toggle()">Toggle</button>