Home > Back-end >  short hand array if statement
short hand array if statement

Time:04-16

Hello I am pretty new to javascript and I am wondering how I could make my code shorter I have an array with multiple items in it and I want to check a few things for each item i can do this with a lot of if statements but i am wondering if there's a "shorthand" way of doing it?

so is it possible to check all items in my array deaths and see which ones have GetComponent('HealthComponent')._alive == 0 ?

var deaths = [];

 if (deaths[0].GetComponent('HealthComponent')._alive == 0) 
     {
this.GetComponent('HealthComponent')._alive = 1;
 this.GetComponent('HealthComponent')._health = 0;
  this.Broadcast({
        topic: 'health.update',
        health: 0,
        maxHealth: 150,
      }); 
      var selected = this;
  setTimeout(function(){
             
                  
            selected.GetComponent('HealthComponent')._health = 150;
             selected.Broadcast({
        topic: 'health.update',
        health: 150,
        maxHealth: 150,
      }); 
      
         
          },60000);
     
         }

 if (deaths[1].GetComponent('HealthComponent')._alive == 0) 
     {
this.GetComponent('HealthComponent')._alive = 1;
 this.GetComponent('HealthComponent')._health = 0;
  this.Broadcast({
        topic: 'health.update',
        health: 0,
        maxHealth: 150,
      }); 
      var selected = this;
  setTimeout(function(){
             
                  
            selected.GetComponent('HealthComponent')._health = 150;
             selected.Broadcast({
        topic: 'health.update',
        health: 150,
        maxHealth: 150,
      }); 
      
         
          },60000);
     
         }

thanks in advance

CodePudding user response:

You can use a for loop, for example:

for (let i = 0; i < deaths.length; i  ) {
  if (deaths[i].GetComponent('HealthComponent')._alive == 0) {
   // do your stuff...
  }
}

or you can use forEach() built-in method of Array, same thing but a little more declarative:

death.forEach(death => {
  if (death.GetComponent('HealthComponent')._alive == 0) {
   // do your stuff...
  }
})

Some docs for you:

About loops in JS

About Array.forEach

  • Related