Javascript Map ordering

狂风中的少年 提交于 2019-12-11 16:05:34

问题


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;

and then, after populating it, i iterate over its contents with a simple for .. of statement. Like this

for (let [key, val] of myMap) { 
    ...
}

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.

Is there something better?


回答1:


The code in for loop depends on (key, value) pair to be sorted by key.

Then a Map is the wrong data structure for you. Its purpose is fast lookup, not maintaining an order. If you need an ordered sequence, use an array. Or if you need both lookup and order, then use both in combination. For your particular case with a small number of known keys, pre-populating the map is fine, alternatively use them only for the iteration

for (let key=0; key < maxkey; key++) {
    if (myMap.has(key)) {
        const val = myMap.get(key);
        … // use key and value
    }
}

Or if there are much more keys than stored in the map, you can also do

for (const key of Array.from(myMap.keys()).sort((a, b) => a-b)) {
    const val = myMap.get(key);
    … // use key and value
}

If you have to do this more than once, you might also want to implement your own iterator.




回答2:


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.



来源:https://stackoverflow.com/questions/50069004/javascript-map-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!