0

i have a piece of code like below

var abc = 
{
2: {label: "raju"},
10: {label: "samu"},
3:  {label: "sidh"}, 
1:  {label: "kat"}, 

};

for(var i in abc){ alert(i); }

in mozilla fire fox it alerts 2,10,3,1. but in chrome it shows 1,2,3,10

but my requirement is the first one (as shown in fire fox) what to do for getting the same result in chrome?

2
  • possible duplicate of Elements order - for (... in ...) loop in javascript Commented Sep 21, 2010 at 10:17
  • for(var i in abc) is not what you think it is (an array element iterator). If you use a normal indexed for loop, and a normal array, surprises you will not get. Commented Sep 21, 2010 at 10:19

1 Answer 1

1

The order in which the "for(var i in ...)" retrieves the items is not defined. For an array-like behaviour you have to use an array ;)

var abc = [
  { nr: 2, label: "raju" },
  { nr: 10, label: "samu" },
  { nr: 3, label: "sidh" },
  { nr: 1, label: "kat" }
];

for (var i = 0, length = abc.length; i < length; i++)
   alert(abc[i].nr);
Sign up to request clarification or add additional context in comments.

1 Comment

A hasOwnProperty check is usually a good idea in a for...in loop: if (abc.hasOwnProperty(i)) {...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.