我有以下数组:
[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);
控制台:总计 = 60