Using map() on an iterator

后端 未结 8 1817
误落风尘
误落风尘 2021-02-01 11:59

Say we have a Map: let m = new Map();, using m.values() returns a map iterator.

But I can\'t use forEach() or map() o

8条回答
  •  死守一世寂寞
    2021-02-01 12:16

    This simplest and most performant way is to use the second argument to Array.from to achieve this:

    const map = new Map()
    map.set('a', 1)
    map.set('b', 2)
    
    Array.from(map, ([key, value]) => `${key}:${value}`)
    // ['a:1', 'b:2']
    

    This approach works for any non-infinite iterable. And it avoids having to use a separate call to Array.from(map).map(...) which would iterate through the iterable twice and be worse for performance.

提交回复
热议问题