为什么 .map() 会产生两个不同的输出?
Why .map() produces two different output?
为什么 .map(() => x + 3) 与 .map((x) => x +3) 产生两个不同的结果?
请参阅下面的代码片段。我有以下代码 app.component.ts
obs = Observable.of(1, 2, 3, 4);
ngOnInit() {
this.usingMapToMakeInnerObservable();
}
usingMapToMakeInnerObservable() {
this.obs
.map(x => Observable.timer(500).map(() => x + 3)) // A. Output 4, 5, 6, 7
//.map(x => Observable.timer(500).map((x) => x + 3)) // B. Output 3, 3, 3, 3
.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log('done completed')
);
}
第一种情况
.map(x => //here x value can be `1, 2, 3, 4`
Observable.timer(500).map(() => x + 3) // x will hold from last map
)
在上面的代码中,首先 x 可以保存值 1, 2, 3, 4
,然后我们应用 Observable.timer
。之后在 .map
中 x 将具有数组的当前项。
如第二种情况
.map(x => //here x value can be `1, 2, 3, 4`
Observable.timer(500).map((x) => x + 3) //x here it has own x so
)
在上面的代码中,第一个映射 x 值可以包含 1, 2, 3, 4
个值。当我们为 timer
Observable 声明 x
时。现在 x
将不再是父地图的 x
值。那么你一定是为什么它不断 Output: 3,3,3,3
的原因。原因是当我们没有向 timer
(Observable) 提及任何其他参数时,它每次都 returns 0
。
为什么 .map(() => x + 3) 与 .map((x) => x +3) 产生两个不同的结果?
请参阅下面的代码片段。我有以下代码 app.component.ts
obs = Observable.of(1, 2, 3, 4);
ngOnInit() {
this.usingMapToMakeInnerObservable();
}
usingMapToMakeInnerObservable() {
this.obs
.map(x => Observable.timer(500).map(() => x + 3)) // A. Output 4, 5, 6, 7
//.map(x => Observable.timer(500).map((x) => x + 3)) // B. Output 3, 3, 3, 3
.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log('done completed')
);
}
第一种情况
.map(x => //here x value can be `1, 2, 3, 4`
Observable.timer(500).map(() => x + 3) // x will hold from last map
)
在上面的代码中,首先 x 可以保存值 1, 2, 3, 4
,然后我们应用 Observable.timer
。之后在 .map
中 x 将具有数组的当前项。
如第二种情况
.map(x => //here x value can be `1, 2, 3, 4`
Observable.timer(500).map((x) => x + 3) //x here it has own x so
)
在上面的代码中,第一个映射 x 值可以包含 1, 2, 3, 4
个值。当我们为 timer
Observable 声明 x
时。现在 x
将不再是父地图的 x
值。那么你一定是为什么它不断 Output: 3,3,3,3
的原因。原因是当我们没有向 timer
(Observable) 提及任何其他参数时,它每次都 returns 0
。