【发布时间】:2018-04-06 12:47:53
【问题描述】:
我有一个字符串数组,看起来像这样(每次都是随机的)
["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"]
然后我循环遍历这个数组,根据索引我调用不同的.subscribe 并将一些数据推送到新数组。
for (var i = 0; i < arrayOfItems.length; i++) {
switch (arrayOfItems[i]) {
case 'spells':
this.spellsSubscribeSet = true;
this.spellsSubscribe = this.spells.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
case 'characters':
this.charactersSubscribeSet = true;
this.charactersSubscribe = this.characters.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
case 'consumables':
this.consumablesSubscribeSet = true;
this.consumablesSubscribe = this.consumables.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
default:
return null;
}
}
.getRandom 是一个返回随机数的普通函数。
getRandom(x) {
return Math.floor(Math.random() * x);
}
只有“法术”才会被多次调用的奇怪东西。
我读过一些关于 .flatMap 的内容,但我认为这对我没有帮助,因为我正在循环一个普通数组。
我正在使用 Firestore 数据库
【问题讨论】:
-
为什么要订阅多次?每当有事情发生时,订阅的目的不是要通知吗?因此,您应该简单地为每个事件订阅一次,工作就完成了。忘记
switch里面的for。 -
或者至少不要重复你自己。
this[arrayOfItems[i]].subscribe将涵盖您的所有案例,如果您有 50 个不同的项目,而不是重复您的代码 50 次。 -
@JeremyThille 您的 cmets 让我想到了可以实现此功能的其他方法。所以现在我在构造函数加载时将我需要的这 3 个集合保存在变量中。然后当我稍后在代码中调用它时,它可以完美运行。
标签: javascript arrays angular typescript google-cloud-firestore