3 回答
TA贡献1818条经验 获得超8个赞
您可以尝试三元条件。
如果 TransporterSmall 优于零,则第二部分是一个对象,因此它被推动。如果不优于零,则为 null(不推送任何内容):
document.getElementById('AutoSelect').onclick = function() {
fleetDispatcher.shipsToSend = []; // Empty array
fleetDispatcher.shipsToSend.push(
TransporterSmall > 0 ? {id:202,number: TransporterSmall} : null,
etc...
fleetDispatcher.refresh();
};
TA贡献1848条经验 获得超6个赞
您可以使用数组过滤和扩展运算符来完成此操作:
document.getElementById('AutoSelect').onclick = function() {
fleetDispatcher.shipsToSend = []; // Empty array
fleetDispatcher.shipsToSend.push(...([
{id:202,number: TransporterSmall},
{id:203,number: TransporterLarge},
{id:208,number: ColonyShip},
{id:209,number: Recycler},
{id:210,number: Probe},
{id:204,number: FighterLight},
{id:205,number: FighterHeavy},
{id:206,number: Cruiser},
{id:207,number: Battleship},
{id:215,number: Interceptor},
{id:211,number: Bomber},
{id:213,number: Destroyer},
{id:214,number: Deathstar},
{id:218,number: Reaper},
{id:219,number: Explorer}]
.filter(item -> item.number !== 0))
);
fleetDispatcher.refresh();
};
(我还没有彻底检查上面的语法,但这至少是我所了解的。)
基本思想是:
取出一长串项目,然后将它们放在方括号中,将它们变成一个数组。
用于
filter
清除所有number
为 0 的数组项。使用扩展运算符 (
...
) 将数组重新转换为 的参数列表push
,但现在零计数项目消失了。
TA贡献1780条经验 获得超3个赞
终于成功了。过滤器是关键。感谢帮助 !
document.getElementById('AutoSelect').onclick = function() {
let ships = [
{id:202,number: TransporterSmall},
{id:203,number: TransporterLarge},
{id:208,number: ColonyShip},
{id:209,number: Recycler},
{id:210,number: Probe},
{id:204,number: FighterLight},
{id:205,number: FighterHeavy},
{id:206,number: Cruiser},
{id:207,number: Battleship},
{id:215,number: Interceptor},
{id:211,number: Bomber},
{id:213,number: Destroyer},
{id:214,number: Deathstar},
{id:218,number: Reaper},
{id:219,number: Explorer}
];
fleetDispatcher.shipsToSend = []; // Empty array
fleetDispatcher.shipsToSend = ships.filter(id => id.number > 0);
fleetDispatcher.refresh();
};
添加回答
举报