JavaScript - 维护对象键值顺序

时间:2017-07-11 16:10:39

标签: javascript json object

我的必需对象键值(属性值)顺序:{three:3,two:2,one:1}

我希望最后添加的键位于顶部,当我动态添加键值时,我得到的顺序如下:

var numObj={};   
numObj["one"]=1;   
numObj["two"]=2; 
numObj["three"]=3;  
console.log(numObj) // result i get is  { one:1, three:3,two:2 } 

请任何人帮我获取此键值订单{three:3,two:2,one:1}

enter image description here

1 个答案:

答案 0 :(得分:1)

正如评论者指出的那样,JavaScript对象没有定义迭代的顺序。但是,JavaScript 地图执行:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

let aMap = new Map();
myMap.set('AKey1', 'AValue1');
myMap.set('AKey2', 'AValue2');
myMap.set('AKey3', 'AValue3');

for (let x of aMap) {
  console.log(x[1]);
}

将提供

AValue1
AValue2
AValue3