如何按照编写的顺序迭代javascript对象属性 [英] How to iterate javascript object properties in the order they were written
问题描述
我发现我的代码中存在一个错误,希望通过最少的重构努力来解决。 Chrome和Opera浏览器中会出现此错误。
问题:
I identified a bug in my code which I hope to solve with minimal refactoring effort. This bug occurs in Chrome and Opera browsers. Problem:
var obj = {23:"AA",12:"BB"};
//iterating through obj's properties
for(i in obj)
document.write("Key: "+i +" "+"Value: "+obj[i]);
FF输出,IE
键:23价值:AA
关键: 12价值:BB
Output in FF,IE Key: 23 Value: AA Key: 12 Value: BB
Opera和Chrome中的输出(错误)
键:12值BB >
关键:23价值AA
Output in Opera and Chrome (Wrong)
Key: 12 Value BB
Key: 23 Value AA
我试图制作一个这样的逆序对象
I attempted to make an inverse ordered object like this
var obj1={"AA":23,"BB":12};
for(i in obj1)
document.write("Key: "+obj[i] +" "+"Value: "+i);
然而输出是相同的。是否有办法通过较小的更改获得所有浏览器相同的行为?
However the output is the same. Is there a way to get for all browser the same behaviour with small changes?
推荐答案
否。 JavaScript对象属性没有固有的顺序。总算很幸运,在循环运行时,的顺序是什么。
No. JavaScript Object properties have no inherent order. It is total luck what order a for...in
loop operates.
如果你想订购,你会必须改为使用数组:
If you want order you'll have to use an array instead:
var map= [[23, 'AA'], [12, 'BB']];
for (var i= 0; i<map.length; i++)
document.write('Key '+map[i][0]+', value: '+map[i][1]);
这篇关于如何按照编写的顺序迭代javascript对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!