RxJS:创建运算符count

count()接收带有值的Observable,并将其转换为将提供单个值的Observable。count函数将谓词函数作为可选参数。该函数的类型为boolean,仅当值是true时才将值添加到输出中。

语法

这是Count的语法:

count(predicate_func? : boolean): Observable

参量

predicate_func-(可选)此函数将从源源中过滤要计数的值并返回布尔值。

返回值

返回值是一个可观察值,具有给定数字的计数。

让我们看一些没有谓词和有功能的计数例子。

例子1

以下示例不带谓词功能:

import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
final_val.subscribe(x => console.log("The count is "+x));

输出

The count is 6

例子2

以下示例具有谓词功能:

import { of } from 'rxjs';
import { count } from 'rxjs/operators';
let all_nums = of(1, 6, 5, 10, 9, 20, 40);
let final_val = all_nums.pipe(count(a => a % 2 === 0));
final_val.subscribe(x => console.log("The count is "+x));

我们在计数中使用的功能是仅对偶数进行计数。

输出

The count is 4

作者:terry,如若转载,请注明出处:https://www.web176.com/rxjs/1806.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年2月8日 下午12:15
下一篇 2021年2月8日 下午2:57

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注