Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
Subtract method in object if greater than zero

I'm using a game object that has different getters and methods within it. One of the parameters of my assignment is that the "playerDies" method has to subtract 1 from the lives if it is greater than zero and it cannot go below 0 (so it can't be -1 which is what is happening now). This topic is fairly new to me so I'm not sure what I can do to execute the subtraction only when there is a specific value. I've tried using an if-else statement but that resulted in the code not working. My code:

var game = {
    lives: 3,
    coins: 0,

    get points() {
        return this.coins * 10;
    },

    playerDies: function() {
            return this.lives -= 1;
    },

    newGame: function() {
         this.lives = 3;
         this.coins = 0;
    },
};


console.log("lives = " + game.lives);    // should be 3
console.log("coins = " + game.coins);    // should be 0
console.log("points = " + game.points);  // should be 0
game.coins = 0;
console.log("points = " + game.points);  // should be 20
game.playerDies();
console.log("lives = " + game.lives);    // should be 2
game.playerDies();
game.playerDies();
game.playerDies();
console.log("lives = " + game.lives);    // should be 0
game.newGame();
console.log("lives = " + game.lives);    // should be 3
console.log("coins = " + game.coins);    // should be 0
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can put if statement in your playerDies method

playerDies: function() {
  if (this.lives > 0) {
    return this.lives -= 1
  }

  return 0
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda