How to iterate javascript object properties in the order they were written -


i identified bug in code hope solve minimal refactoring effort. bug occurs in chrome , 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]); 

output in ff,ie key: 23 value: aa key: 12 value: bb

output in opera , chrome (wrong)
key: 12 value bb
key: 23 value aa

i attempted make inverse ordered object this

var obj1={"aa":23,"bb":12}; for(i in obj1)   document.write("key: "+obj[i] +" "+"value: "+i); 

however output same. there way browser same behaviour small changes?

no. javascript object properties have no inherent order. total luck order for...in loop operates.

if want order you'll have use array instead:

var map= [[23, 'aa'], [12, 'bb']]; (var i= 0; i<map.length; i++)     document.write('key '+map[i][0]+', value: '+map[i][1]); 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -