Javascript地图排序 [英] Javascript Map ordering
问题描述
我最近在我的代码中存在一个错误,这是由于我在查看MDN上的Map对象详细信息时缺少"插入顺序"文本.简而言之,我有一个地图对象,可以说
i recently had a bug in my code that was due to me missing the "in insertion order" text while looking through Map object details on MDN. In short, i have a map object, lets say
let myMap = new Map;
,然后在填充它之后,用简单的 for .. of 语句遍历它的内容.像这样
and then, after populating it, i iterate over its contents with a simple for .. of statement. Like this
for (let [key, val] of myMap) {
...
}
for 循环中的代码取决于要按 key 排序的(键,值)对.但是,填充地图的算法是按照随机顺序进行的(我无法更改).为了解决这个问题,我现在首先将所有可能的键添加到地图对象中,如下所示:
The code in for loop depends on (key, value) pair to be sorted by key. However the algorithm that populates the map, does so in a random order(and i can't change that). To get around this problem, i now add all possible keys to the map object first, something like this:
let myMap = new Map;
for (let i=0; i<maxkey; ++i) myMap.set(key(i), undefined);
// And in the for loop
for (let [key, val] of myMap) {
if (typeof val === "undefined") continue;
//...
}
幸运的是,它们并不多(因此性能损失可以忽略不计),并且这种方法可行.对于我来说,这种解决方案还是有点尴尬.
Fortunately, there aren't many of them(so the performance penalty is negligible), and this works. Still this solution looks a bit awkward to me.
还有更好的东西吗?
推荐答案
地图中键的顺序取决于地图的实现.具有自然排序键的地图通常称为树图,因为这些密钥存储在
The ordering of keys in a map depends on the map implementation. A map with naturally ordered keys is often called a tree map because the keys are stored in a tree. I have not used a tree map in JS so I can't recommend a particular implementation.
这篇关于Javascript地图排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!