问题
How can I create an associative array that guarantees order?
Object (not guarantee order):
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) {
console.log(i);
};
Result:
1
2
34
first
second
Array:
var a = new Array();
a['first'] = "first";
a['2'] = "2";
a['34'] = "34";
a['1'] = "1";
a['second'] = "second";
console.log(a); // [1: "1", 2: "2", 34: "34", first: "first", second: "second"]
for (var i in a) {
console.log(i);
};
Result:
1
2
34
first
second
The array does not guarantee order at all.
How can I create a correct array that guarantees order then?
回答1:
In ECMAScript 6 Map type is an ordered list of key-value pairs, where both the key and the value can have any type. A Map object iterates its elements in insertion order.
The forEach method executes a provided function once per each key/value pair in the Map object, in insertion order.
var a = new Map;
a.set("first", "first");
a.set("2", "2");
a.set("34", "34");
a.set("1", "1");
a.set("second", "second");
a.forEach(function(value, key) {
console.log(key + ' => ' + value)
})
You can also use for...of loop and it returns an array of [key, value] for each iteration.
var a = new Map;
a.set("first", "first");
a.set("2", "2");
a.set("34", "34");
a.set("1", "1");
a.set("second", "second");
for (var p of a) console.log(p)
回答2:
You cannot save properties in a specific order in object, but you can parse it while printing in any custom order. You will have to create another array of values or if to be printed on document, then an HTML string.
You can try something like this:
Note: You can check using comparison operator > or <. You can parse numeric values and compare or string compare non-numeric values, but will give issues if you have something like eleven.
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
var sortOrder = ["1", "2", "34", "first", "second"];
var html = Object.keys(obj).sort(function(a,b){
var _a = getSortPosition(a);
var _b = getSortPosition(b);
return _a> _b ? 1: _a<_b ? -1 : 0;
}).map(function(item){
return "<span>" +item+ "</span>";
}).join("<br/>");
document.getElementById("content").innerHTML = html;
function getSortPosition(key){
var _index = sortOrder.indexOf(key);
return _index >-1 ? _index : 999;
}
<div id="content"></div>
来源:https://stackoverflow.com/questions/38102982/javascript-how-to-create-an-associative-array-that-guarantees-order