大网数据广告活动
Web 标准与前端开发

Observable: filter() method

· 52CE 我爱测

The **`filter()`** method of the Observable interface returns a new observable that emits only those values of the source observable for which the provided callback function returns a truthy value.

Observable API

The filter() method of the Observable interface returns a new observable that emits only those values of the source observable for which the provided callback function returns a truthy value.

Syntax

filter(predicate)

Parameters

  • predicate
    • : A function to execute for each value emitted by the source observable. It should return a truthy value to have the value emitted by the returned observable, and a falsy value otherwise. The function is called with the following arguments:
      • value
        • : The current value being processed.
      • index
        • : The index of the current value being processed, starting from 0.

Return value

A new Observable. When subscribed to, it calls predicate for each value emitted by the source observable and emits the value only if predicate returns a truthy value. When the source completes, the returned observable also completes.

Description

Like other observable-returning operators, this method is lazy: calling it creates a new observable without subscribing to the source. Processing starts when the returned observable is subscribed to.

If predicate throws an exception, the returned observable errors and unsubscribes from the source. Errors from the source are also forwarded.

The index counts all source values, including those that are filtered out. The return value of predicate is converted to a boolean without awaiting it, so an async function returns a truthy promise object regardless of its eventual result.

Examples

Using filter()

This example displays the mouse coordinates only when the pointer moves over either of two <div> elements. The filter excludes events whose target is another element.

<div></div>
<div></div>
<p></p>
div {
  height: 120px;
  background-color: purple;
  margin-bottom: 40px;
}
const outputElem = document.querySelector("p");

document.body
  .when("mousemove")
  .filter((e) => e.target.matches("div"))
  .map((e) => ({ x: e.clientX, y: e.clientY }))
  .subscribe({ next: reportCoords });

function reportCoords(e) {
  outputElem.textContent = `${e.x},${e.y}`;
}

basic-filter

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。