简体   繁体   English

如何使用Javascript / TypeScript减少总和

[英]How to calculate total using Javascript/ TypeScript reduce

I have the following array: 我有以下数组:

[Title1: 111, Title2: 222, Title3: 333]

This array is generated from a Web Socket Service and I want to accumulate the values using reduce. 该数组是从Web套接字服务生成的,我想使用reduce来累积值。

I have the following code, but I can't get it to work: 我有以下代码,但无法正常工作:

this.liveDataPriceTotal = this.liveDataPrice.reduce( ( previousValue, currentValue ) => Number( previousValue ) + Number( currentValue ), 0 );

Where replacing this.liveDataPrice with [111, 222, 333] works as expected. 在将this.liveDataPrice替换为[111,222,333]的地方按预期工作。

Any ideas how to get the accumulated total from my array? 有什么想法如何从我的阵列中获得累加总数吗?

Solution: 解:

Since I was confused and mixed up arrays and objects, I came with the following solution which accumulates the values from my object: 由于我很困惑并且混淆了数组和对象,因此我想到了以下解决方案,该解决方案累积了对象中的值:

this.liveDataVolume24hTotal = Object.entries( this.liveDataVolume24h ).reduce( function( total, [key, value] ) {
    return ( value ? Number( total ) + Number( value ) : total );
}, 0 );

Simple exemple: 简单示例:

total: number = 0;
arrayNumb: [10, 20, 30];

this.total = this.arrayNumb.reduce((a, b) => a + b);
console.log('TOTAL = ', this.total);

console: TOTAL = 60 控制台: TOTAL = 60

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM