问题
Java has LinkedHashMap
but there doesn't seem to be a similar solution in JavaScript.
Basically, I want to be able to say
var map = {};
map['a'] = 1;
map['b'] = 2;
Then when I iterate over the map, they are always in [{a:1}, {b:2}...] order.
回答1:
I believe JavaScript Map object can help you to solve this issue:
let myObject = new Map();
myObject.set('z', 33);
myObject.set('1', 100);
myObject.set('b', 3);
for (let [key, value] of myObject) {
console.log(key, value);
}
// z 33
// 1 100
// b 3
Also, please take into consideration that this is ES6 (ES2015) standard. Cheers.
回答2:
You can use a second array to preserve the order of keys.
var order = [];
//add something to map
map['a'] = 1;
order.push('a');
map['b'] = 2;
order.push('b');
//iterate in order
for (var i=0; i< order.length;++i) {
alert(map[order[i]);
}
Preserving consistency of the order array might be tricky since you always need to update the order array when you modify the original map.
来源:https://stackoverflow.com/questions/25041814/how-to-preserve-order-of-hashmap-in-javascript