Jim Lynch Codes
  • Blog
  • About Jim

For... In vs For Each ... In

This is a very important aspect of programming that I had forgotten about. I am embarrassed to that that I was tripped up by this difference this morning. In addition to everyone’s favorite language, actionscript 3, this basic feature of for in and for each in occurs in many languages like javascript, c#, java, python, and many more. So even though this post uses as3 syntax, it’s a much broader programming concept than some topics that are flash specific.

I’m talking here of course about the difference between for in and for each in.

I was trying to read in the flash vars for a flash application. In my Main.as I wanted to loop through all the flash vars that were passed into the swf.

For simplicity, let’s say I passed in these flash vars:

url1=http://goop.com
url2=http://moop.com
url3=http://floop.com

Well, simple enough. I did it like this:
var paramObj:Object = this.root.loaderInfo.parameters
    for  (var param:String in paramObj)
    {
        trace(“key?: “ + param);
    }
I wanted to loop through and get all of the flash vars, and I did. This code compiles fine and works, but it prints out this:

key?: http://goop.com
key?: http://moop.com
key?: http://floop.com

Hmm, well this isn’t what I wanted. I wanted to get url1, url2, … in the code. So after a while of digging around online I realized that the ‘each’ keyword was giving me problems. If I took out the each, and wrote the code like this:
var paramObj:Object = this.root.loaderInfo.parameters
for (var param:String in paramObj)
    {
        trace(“key: “ + param);
    }
Then we now get the “keys” for the flash vars as they are called:

key: url1
key: url2
key: url3

If you wanted the value, for example for the first flash var, you just do paramObj[param]

Aha! So now we can see that clearly there is a difference between a for in loop and afor each in loop. Remember,

for-in loops over indexes (or keys), and for-each-in loops over values.
  • Blog
  • About Jim
JimLynchCodes © 2021