JavaScript-如何创建一个保证顺序的关联数组? [英] JavaScript - How to create an associative array that guarantees order?
问题描述
如何创建保证订单的关联数组?
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) {
console.log(i);
};
结果:
1
2
34
first
second
数组:
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);
};
结果:
1
2
34
first
second
该数组根本不能保证顺序.
The array does not guarantee order at all.
如何创建一个可以保证顺序的正确数组?
How can I create a correct array that guarantees order then?
推荐答案
在ECMAScript 6中,映射类型是键-值对的有序列表,其中键和值都可以具有任何类型. Map对象按插入顺序对其元素进行迭代.
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.
forEach
方法按插入顺序对Map对象中的每个键/值对执行一次提供的功能.
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)
})
您还可以使用for...of
循环,它会为每次迭代返回一个[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)
这篇关于JavaScript-如何创建一个保证顺序的关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!