如何从列表中计算总和 — Typescript - Angular2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39214621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate sum from a list — Typescript - Angular2
提问by Bea
New in TypeScript — Angular 2.
TypeScript 的新功能 — Angular 2。
I wondering to know how to calculate a sum from a list.
我想知道如何从列表中计算总和。
I already selected the items needed and get the sum with a error :
我已经选择了所需的项目并得到了错误的总和:
TS Error Type 'void' is not assignable to type 'Creance[]',
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);
}
It seems 'forEach' is not used correctly.
似乎 'forEach' 没有正确使用。
Is it possible to add the filter and the forEach in the same time ?
是否可以同时添加过滤器和 forEach ?
thanks Bea
谢谢贝
回答by Nitzan Tomer
Instead of using forEachyou should use mapto return the numbers you want to sum up, and then use reduceto sum them:
您应该使用map来返回要求和的数字,而不是使用forEach,然后使用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);
}
You can remove a cycle of iterations by filtering out the items in the mapping:
您可以通过过滤掉映射中的项目来删除迭代循环:
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);
}