是否可以对 ES6 地图对象进行排序? [英] Is it possible to sort a ES6 map object?
本文介绍了是否可以对 ES6 地图对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以对 es6 地图对象的条目进行排序?
Is it possible to sort the entries of a es6 map object?
var map = new Map();
map.set('2-1', foo);
map.set('0-1', bar);
结果:
map.entries = {
0: {"2-1", foo },
1: {"0-1", bar }
}
是否可以根据键对条目进行排序?
Is it possible to sort the entries based on their keys?
map.entries = {
0: {"0-1", bar },
1: {"2-1", foo }
}
推荐答案
根据 MDN 文档:
Map 对象按插入顺序迭代其元素.
A Map object iterates its elements in insertion order.
你可以这样做:
var map = new Map();
map.set('2-1', "foo");
map.set('0-1', "bar");
map.set('3-1', "baz");
var mapAsc = new Map([...map.entries()].sort());
console.log(mapAsc)
使用.sort()
,记住数组是根据每个字符的Unicode码位值排序的,根据每个元素的字符串转换.所以 2-1, 0-1, 3-1
会被正确排序.
Using .sort()
, remember that the array is sorted according to each character's Unicode code point value, according to the string conversion of each element. So 2-1, 0-1, 3-1
will be sorted correctly.
这篇关于是否可以对 ES6 地图对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文