TypeScript中的新功能 - Angular 2。
我想知道如何从列表中计算总和。
我已经选择了所需的项目并获得了错误:
TS错误类型'void'不能分配给'Creance []',
creancesOfSelectedRemise: Creance[];
onSelectRemise(remise: Remise, event: any) {
...//...
this.creancesOfSelectedRemise = this.creances
.filter(c => c.id_remettant === remise.id_remettant)
.forEach(c => this.totalCreances += c.creance_montant);
}
似乎'forEach'未正确使用。
是否可以同时添加过滤器和forEach?
感谢 衣
答案 0 :(得分:24)
您应该使用forEach来返回要汇总的数字,而不是使用map,然后使用reduce对它们求和:
onSelectRemise(remise: Remise, event: any) {
...
this.creancesOfSelectedRemise = this.creances
.filter(c => c.id_remettant === remise.id_remettant)
.map(c => c.creance_montant)
.reduce((sum, current) => sum + current);
}
您可以通过过滤掉映射中的项目来删除迭代循环:
onSelectRemise(remise: Remise, event: any) {
...
this.creancesOfSelectedRemise = this.creances
.map(c => c.id_remettant === remise.id_remettant ? c.creance_montant : 0)
.reduce((sum, current) => sum + current);
}