Google analytics code

Friday, March 12, 2010

ActionScript: The difference between "FOR IN" and "FOR EACH"

I ran into an issue earlier while looping through a list of objects where I couldn't get the index of the array I was accessing. Turns out there is a BIG difference between FOR and FOR EACH. Coding late at night probably didn't help either.

FOR EACH gives you access to the element in the array. FOR gives you access to the index of the array.

var elements:Array = [{name:'Orange'}, {name:'Apple'},{name:'Banana'},{name:'Pear'}];

for(var i:Object in elements) {
    trace("index: " + i);
}

for each(var e:Object in elements) {
    trace("element: " + e.name);
}

The output from FOR loop looks like this:
index: 0
index: 1
index: 2
index: 3

The output from FOR EACH looks like this:
element: Orange
element: Apple
element: Banana
element: Pear

Hopefully this helps someone from blunt force trauma caused by baning your head against the desk. Probably common knowledge for most, but it never hurts to post it.

5 comments:

  1. its actually 'for in' vs 'for each'. 'for' looks like:

    for (var d:int=0;d<6;d++)
    {
    trace("index: " + d);
    }

    ReplyDelete
  2. Good point. I'll update the name.

    ReplyDelete
  3. I would like to say that i found this to be very useful, thank you!

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.