简体   繁体   English

使用 reduce() 函数实现此例程的正确方法是什么?

[英]what is the proper way to implement this routine with reduce() function?

I'm trying to sum all of the Total values in a commodityDeliveries array into a TotalOfMaterial property as shown below:我正在尝试将商品交付数组中的所有 Total 值汇总到 TotalOfMaterial 属性中,如下所示:

let grandTotalsFooter = {};
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.reduce(x => x.Total);

I know that a proper reduce() implementation is not as simple as what I have above but just providing the general intent of what I'm trying to do.我知道一个适当的 reduce() 实现并不像我上面的那么简单,而只是提供我想要做的事情的一般意图。 What is the proper and simplest way to do this with the reduce() function?使用 reduce() 函数执行此操作的正确且最简单的方法是什么? Also, is there a popular third-party js lib which simplifies this kind of routine with a sum() function similar to the .NET framework as follows?:另外,是否有一个流行的第三方 js 库,它使用类似于 .NET 框架的 sum() 函数简化了这种例程,如下所示?:

let grandTotalsFooter = {};
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.sum(x => x.Total);

The .NET sum() function is much more straightforward and intuitive. .NET sum() 函数更加直接和直观。 I would think that the JS standards would introduce a sum() function like this at some point?我认为 JS 标准会在某个时候引入这样的 sum() 函数?

The function passed to reduce must take two parameters (or more): an accumulator, and the current item.传递给reduce的函数必须接受两个(或更多)参数:一个累加器和当前项。 So your assignment becomes:所以你的任务变成:

grandTotalsFooter.TotalOfMaterial = commodityDeliveries.reduce((acc, item) => acc+item.Total);

See the MDN for more details on Array.prototype.reduce() . 有关Array.prototype.reduce()更多详细信息,请参阅 MDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 TypeScript 中实现“toJson”function 的正确方法是什么? - What is the proper way to implement a 'toJson' function in TypeScript? 实现此JSON.parse的正确方法是什么? - what is the proper way to implement this JSON.parse? 实现常量的正确方法是什么? - What's the proper way to implement constant variable? 在 Firebase 中实施身份验证的正确方法是什么? - What is the proper way to implement authentication in Firebase? 为Javascript函数转义HTML的正确方法是什么? - What is a proper way to escape HTML for Javascript function? 呈现异步 function 的正确方法是什么? - What is the proper way to render an async function? 实现此自定义打字稿模块的正确方法是什么? - what's the proper way to implement this custom typescript module? 实现AngularJS控制器中使用的可重用JavaScript对象的正确方法是什么? - What is the proper way to implement a reusable JavaScript object used in AngularJS controllers? 筛选ViewModel存储并实现到ExtJS Panel的正确方法是什么? - What is the proper way to filtering ViewModel stores and implement to ExtJS Panel? 使用变量在 VueJs 中使用 SASS 实现暗模式的正确方法是什么 - what's the proper way to implement darkmode in VueJs with SASS using variables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM