我正在研究RXJS并坚持这个问题:运算符"reduce"和"scan"的相同代码以不同的方式工作,但我认为必须返回相同的结果.以下示例.请帮忙.
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" - …
Run Code Online (Sandbox Code Playgroud)