RxJS – Creation Operator Count



count() 接收帶有值的 Observable,將其轉換為將提供一個單一值的 Observable。count 函式接收謂詞函式作為可選引數。該函式的型別為布林值,僅當值是真值時才將值新增到輸出。

語法

以下是 Count 語法 −

count(predicate_func? : boolean): Observable

引數

predicate_func - (可選) 將篩選源 observable 中待計數的值並返回布林值的函式。

返回值

返回值是一個包含給定數字計數的 observable。

讓我們看看一些沒有謂詞和帶有函式的 count 的示例。

示例 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));

我們再 count 中使用的函式僅提供偶數的計數。

輸出

The count is 4
廣告
© . All rights reserved.