你好,我對 javascript 還是很陌生,我想知道如何讓我的代碼更短我有一個包含多個專案的陣列,我想為每個專案檢查一些事情,我可以用很多 if 陳述句來做到這一點,但我我想知道是否有一種“速記”方式來做到這一點?
那么是否可以檢查我的陣列中的所有專案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);
}
提前致謝
uj5u.com熱心網友回復:
您可以使用 for 回圈,例如:
for (let i = 0; i < deaths.length; i ) {
if (deaths[i].GetComponent('HealthComponent')._alive == 0) {
// do your stuff...
}
}
或者你可以使用forEach()Array 的內置方法,同樣的事情,但更具宣告性:
death.forEach(death => {
if (death.GetComponent('HealthComponent')._alive == 0) {
// do your stuff...
}
})
為您準備的一些檔案:
關于 JS 中的回圈
關于 Array.forEach
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460413.html
標籤:javascript 数组 if 语句
上一篇:使用遞回,我如何讓我的代碼重復?
