RxJS - 数学运算符 Reduce



在 reduce 运算符中,在输入可观察对象中使用累加器函数,而且累加器函数将以可观察对象的格式返回累加的值,其中有一个可选的种子值传给累加器函数。

reduce() 函数将输入 2 个参数,一个累加器函数,第二个是种子值。

语法

reduce(accumulator_func, seeder?) : Observable

参数

accumulator_func − (可选)。调用可观察对象中源值的函数。

seeder − ((可选) 默认值是未定义。考虑累加的初始值。

返回值

它将返回具有单个累加值的可观察对象。

我们来看一些示例,了解 reduce 运算符是如何工作的。

示例 1

import { from } from 'rxjs';
import { reduce } from 'rxjs/operators';

let items = [
   {item1: "A", price: 1000.00},
   {item2: "B", price: 850.00},
   {item2: "C", price: 200.00},
   {item2: "D", price: 150.00}
];
let final_val = from(items).pipe(reduce((acc, itemsdet) => acc+itemsdet.price, 0));
final_val.subscribe(x => console.log("Total Price is: "+x));

输出

Total Price is: 2200
广告
© . All rights reserved.