是否可以对ES6地图对象进行排序? [英] Is it possible to sort a ES6 map object?
本文介绍了是否可以对ES6地图对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var map = new Map();
map.set('2-1',foo);
map.set('0-1',bar);
结果:
map.entries = {
0:{2-1,foo},
1:{0-1,bar}
}
是否可以根据这些密钥对条目进行排序?
map.entries = {
0:{0-1,bar},
1:{2-1,foo}
}
解决方案
根据MDN文档:
Map对象以插入顺序迭代其元素。
你可以这样做:
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() ()); console.log(mapAsc)
c $ c> .sort(),remem根据每个元素的字符串转换,数组按照每个字符的Unicode代码点值进行排序。所以 2-1,0-1,3-1
将被正确排序。
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);
results in:
map.entries = {
0: {"2-1", foo },
1: {"0-1", bar }
}
Is it possible to sort the entries based on thier keys?
map.entries = {
0: {"0-1", bar },
1: {"2-1", foo }
}
解决方案
According MDN documentation:
A Map object iterates its elements in insertion order.
You could do it this way:
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)
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屋!
查看全文