Hola, soy bastante nuevo en javascript y me pregunto cómo podría acortar mi código. Tengo una matriz con varios elementos y quiero verificar algunas cosas para cada elemento. Puedo hacer esto con muchas declaraciones if pero yo Me pregunto si hay una forma "taquigráfica" de hacerlo.
Entonces, ¿es posible verificar todos los elementos en mi matriz de deaths y ver cuáles tienen 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); }gracias de antemano
Puede usar un bucle for, por ejemplo:
for (let i = 0; i < deaths.length; i++) { if (deaths[i].GetComponent('HealthComponent')._alive == 0) { // do your stuff... } } o puede usar el método incorporado forEach() de Array, lo mismo pero un poco más declarativo:
death.forEach(death => { if (death.GetComponent('HealthComponent')._alive == 0) { // do your stuff... } })Algunos documentos para usted: