“减少”与“减少”之间的区别是什么?和“扫描” [英] What's difference between "reduce" and "scan"

查看:105
本文介绍了“减少”与“减少”之间的区别是什么?和“扫描”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究RXJS并坚持这个问题:运算符reduce和scan的相同代码以不同的方式工作,但我认为必须返回相同的结果。
以下示例。
请帮忙。

I'm studying RXJS and stuck with the problem: the same code with operators "reduce" and "scan" works in different ways, but I think that must return equal result. Example below. Please help.

const txtElement1 = document.getElementById('txt1');
const txtElement2 = document.getElementById('txt2');
const txtElement3 = document.getElementById('txt3');

// function return Observable
function get(array, initValue) {
  return Rx.Observable.create(observer => {
    let timer = initValue;

    array.forEach(item => {
      setTimeout(() => observer.next(item), timer);
      timer += 1000;
    });
  });
}

// 1) don't work with "reduce"
var stream1$ = get(['John', 'Ann', 'Bob'])
  .reduce(function(acc, x) {
    return acc + ` ${x}`;
  }, 'first - ');

stream1$.subscribe(text => txtElement1.innerHTML = text);

// 2)  the same code, but with "scan" - working
var stream2$ = get(['John', 'Ann', 'Bob'])
  .scan(function(acc, x) {
    return acc + ` ${x}`;
  }, 'second - ');

stream2$.subscribe(text => txtElement2.innerHTML = text);

// 3)  and the simple Observable with "reduce" - working
var stream3$ = Rx.Observable.from(['John', 'Ann', 'Bob'])
  .reduce(function(acc, x) {
    return acc + ` ${x}`;
  }, 'third - ');

stream3$.subscribe(text => txtElement3.innerHTML = text);


推荐答案

来自RxJS文档,


扫描

将一个函数应用于Observable发出的每个项目, ,
发出每个连续值

apply a function to each item emitted by an Observable, sequentially, and emit each successive value


减少

将函数应用于Observable发出的每个项目,按顺序,
发出最终值

apply a function to each item emitted by an Observable, sequentially, and emit the final value

示例代码

扫描

Scan

var source = Rx.Observable.range(1, 3)
.scan(
    function (acc, x) {
        return acc + x;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

对于Observable发出的每个值,扫描顺序发出相应的输出,因此输出将有3个值范围1到3,如下所示

For each value emitted by the Observable, scan emits corresponding output sequentially, So the Output will have 3 values for range 1 to 3, as follows

Output
Next: 1
Next: 3
Next: 6
Completed

减少

Reduce

var source = Rx.Observable.range(1, 3)
    .reduce(function (acc, x) {
        return acc * x;
    }, 1)

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Reduce函数将observables的值减少为单个值(final result)和emit。所以输出如下,

Reduce function reduces the values from observables to a single value (final result) and emit. So the output will be as follows,

Next: 6
Completed

这篇关于“减少”与“减少”之间的区别是什么?和“扫描”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆