3 Replies Latest reply on Mar 3, 2010 3:51 AM by gr8momo

# for..in loop array.sortOn problem

Hello,

Can some one explain this for..in loop behaviour, here is the code:

/**************************************************************/

var a:Array = new Array({num:10},{num:9},{num:11});

for(i = 0; i<a.length; i++)
trace(a[i].num);

for(idx in a)
trace("idx: "+idx+"  val: "+a[idx].num);

a.sortOn("num", Array.NUMERIC);

trace("\nafter sort\n")

for(i = 0; i<a.length; i++)
trace(a[i].num);

for(idx  in a)
trace("idx: "+idx+"  val: "+a[idx].num);

/**************************************************************/

Output:

10
9
11
idx: 2  val: 11
idx: 1  val: 9
idx: 0  val: 10

after sort

9
10
11
idx: 1  val: 10
idx: 0  val: 9
idx: 2  val: 11

question: Why is the order of the for..in changing once the array is sorted??

Thanks ppl

• ###### 1. Re: for..in loop array.sortOn problem

for me the output should have been:

10

9

11

idx: 2 val: 11

idx: 1 val: 9

idx: 0 val: 10

after sort

9

10

11

idx: 2 val: 11
idx: 1 val: 10
idx: 0 val: 9

• ###### 2. Re: for..in loop array.sortOn problem

Because that is the way that for...in works. You can't count on any specific order, you can only be sure you'll get all of them.

I'm sure it has to do with how the Array class handles the representations of the data, but I don't know all the details. I would guess that behind the scenes there is some hidden index that keeps track of what order to show them in using a regular in loop and that the for...in doesn't use that and instead uses some kind of memory location or something.