[英]How to calculate total using Javascript/ TypeScript reduce
我有以下数组:
[Title1: 111, Title2: 222, Title3: 333]
该数组是从Web套接字服务生成的,我想使用reduce来累积值。
我有以下代码,但无法正常工作:
this.liveDataPriceTotal = this.liveDataPrice.reduce( ( previousValue, currentValue ) => Number( previousValue ) + Number( currentValue ), 0 );
在将this.liveDataPrice替换为[111,222,333]的地方按预期工作。
有什么想法如何从我的阵列中获得累加总数吗?
解:
由于我很困惑并且混淆了数组和对象,因此我想到了以下解决方案,该解决方案累积了对象中的值:
this.liveDataVolume24hTotal = Object.entries( this.liveDataVolume24h ).reduce( function( total, [key, value] ) {
return ( value ? Number( total ) + Number( value ) : total );
}, 0 );
简单示例:
total: number = 0;
arrayNumb: [10, 20, 30];
this.total = this.arrayNumb.reduce((a, b) => a + b);
console.log('TOTAL = ', this.total);
控制台: TOTAL = 60
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.