简写数组 if 语句

short hand array if statement

你好,我是 javascript 的新手,我想知道如何让我的代码更短 我有一个包含多个项目的数组,我想为每个项目检查一些事情我可以用很多 if 语句来做到这一点,但我想知道是否有“shorthand”的方式来做到这一点?

所以是否可以检查我的数组 deaths 中的所有项目并查看哪些项目具有 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);
     
         }

提前致谢

您可以使用 for 循环,例如:

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

或者您可以使用数组的 forEach() built-in 方法,同样的事情,但更具声明性:

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

一些适合您的文档:

About loops in JS

About Array.forEach