首页 > 解决方案 > rxjs:带索引的地图

问题描述

我想知道使用地图时当前对象的索引。例如:

x = [3,2,6]
from(x).pipe(
 map(index, val => (val, index))
).subscribe((val, index) => console.log(val, index))

预期产出

3, 0
2, 1
6, 2

基本上,我想知道数组中元素的索引。我怎样才能做到这一点?

标签: angularrxjs

解决方案


它与您尝试过的非常接近

from(x).pipe(
 map((val, index) => [val, index]) // here we transform event to array (call it tuple if you like)
).subscribe(([val, index]) => console.log(val, index)) // here in params we destructure tuple to values again

推荐阅读