欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

rxjs 操作符 pairwise 的一个例子

发布时间:2023/12/19 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 rxjs 操作符 pairwise 的一个例子 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Groups pairs of consecutive emissions together and emits them as an array of two values.

pairwise 将连续的发射出的值进行分组并配对,然后以数组的数据结构进行发射。

pairwise 返回的数据类型如下:返回一个新的 OperatorFunction,这是一个函数,该函数返回一个新的 Observable,以数组的结构包裹了源 Observable 发射的值。

OperatorFunction<T, [T, T]>: A function that returns an Observable of pairs (as arrays) of consecutive values from the source Observable.

pairwise 的弹珠图:

下列这段代码,计算每次屏幕点击和前一次点击的绝对距离:

import { fromEvent } from 'rxjs'; import { pairwise, map } from 'rxjs/operators';const clicks = fromEvent(document, 'click'); const pairs = clicks.pipe(pairwise()); const distance = pairs.pipe(map((pair) => {const x0 = pair[0].clientX;const y0 = pair[0].clientY;const x1 = pair[1].clientX;const y1 = pair[1].clientY;return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));}) ); distance.subscribe((x) => console.log(x));

总结

以上是生活随笔为你收集整理的rxjs 操作符 pairwise 的一个例子的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。