How to get a last element of ES6 Map without iterations?

后端 未结 2 360
执念已碎
执念已碎 2020-12-11 15:42

How to get a last element of ES6 Map/Set without iterations(forEach or for of) pass through a full length of the container?

相关标签:
2条回答
  • 2020-12-11 16:00
    const getLastItemInMap = (map) => [...map][map.size-1];
    const getLastKeyInMap = (map) => [...map][map.size-1][0];
    const getLastValueInMap = (map) => [...map][map.size-1][1];
    
    0 讨论(0)
  • 2020-12-11 16:03

    Maps are iterable and ordered, but they are not arrays so they don't have any indexed access. Iterating to the final element is the best you can do. The simplest case being

     Array.from(map.values()).pop();
    
    0 讨论(0)
提交回复
热议问题