Death To Conditional Statements! Loop Through Elements in an Array with 1 Line of Code

by carl schooff on July 26, 2011 · View Comments

in AS3 Tips

This swf illustrates a basic scenario of outputting various elements in an Array in a continuous loop.

This movie requires Flash Player 9

Let’s not waste any time. I’m going to show you how to take all this

function nextDay(e:MouseEvent):void
{
	if (count < numDays - 1)
	{
		count++;
	}
	else
	{
		count = 0;
	}
	day_txt.text = days_array[count];
}

And nuke it down to just this:

function nextDay(e:MouseEvent):void
{

   day_txt.text = days_array[   ++count % numDays  ]

}

interested?

Watch this for 3 minutes at least

*note I apologize that my function is named toggleWindow instead of nextDay in the video. I think youtube was hacked:)

What the heck does % do?

Did you watch the video? Ok, fine. The modulo operator which looks like % does a nifty little trick for us. It takes the number on the left and divides it by the number on the right. When the operation is done, it gives us the REMAINDER.

Consider the following expression

11 % 5 will return 1

why? Because 11 divided by 5 gives us 2 with a remainder of 1.

Still not clear?

5 x 2 = 10

11-10 = 1

Check out the following traces from my modulo demo swf (as seen in the video)

0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2
8 % 5 = 3
9 % 5 = 4
10 % 5 = 0
11 % 5 = 1
12 % 5 = 2
13 % 5 = 3
14 % 5 = 4
15 % 5 = 0
16 % 5 = 1
17 % 5 = 2
18 % 5 = 3
19 % 5 = 4
20 % 5 = 0
21 % 5 = 1
22 % 5 = 2
23 % 5 = 3
24 % 5 = 4

The main take away here is that any value on the left can be converted to a number from 0 to 4. So as our counter goes up, we can always convert it down and force it into our range. This comes in real handy when looping through Arrays, Objects Strings, XMLLists or anything else that is indexed.

Let’s say we clicked our button 22 times and our array has 5 items in it.

Well, 5 goes into 22 4 times.

4 x 5 = 20

22-20 gives us a remainder of 2.

Well 22 clicks would have us sucking the item with an index of 2 out of our array.

I’m sure someone else has already done this, but from this point forward it is perfectly acceptable and expected that all members of the snorklsphere refer to this technique as the schooff loop. thanks.

Download Source Files

schooff_loop_cs4

Notes

1: As Andreas points out in the comments, this will not work going backwards:
The only problem is going backwards, since negative numbers won’t be positive when modulo is applied to them:
trace(-1 % 7); // -1
trace(-2 % 7); // -2
// …
trace(-6 % 7); // -6
trace(-7 % 7); // 0
trace(-8 % 7); // -1

You would still need an “if” in order to make sure numbers aren’t negative and add 7 if they are..

2: As Harry mentioned below, at some point I mis-counted. The full length of the array is 7 so numDays will start at 7 when the days_arr is full.

3: If you want to do a simple toggle switch for play/pause or on/off check out the Conditional-Less Boolean Toggle AKA Switcheroo

thanks guys for your help.

wrap up

Have fun with this one. I’m going easy on you as massive LoaderMax stuff and a new AS3 code challenge are coming soon!

If you found this tip helpful feel free to share it on your social network of choice.

Best,

Carl

Post to Twitter Post to Facebook

  • Merrick Brewer

    Your schooff loop has hurt my brain. Excellent little tutorial again Carl. Can see this finding it’s way into a slide show that I’m developing.

    More please!!!

  • Harry

    Nice tutorial Carl, I never thought of doing it this way before! One thing though, numDays is 7 not 6! Arrays are zero-based but the length property isn’t.

    Looking forward to the next AS3 challenge btw, I found your site after both the previous ones had finished!

  • http://www.snorkl.tv/ carl schooff

    Thanks Harry, You are are exactly right! Sometimes simple counting gets
    wonky when I am recording. doh.

  • http://twitter.com/IQAndreas Andreas Renberg

    The only problem is going backwards, since negative numbers won’t be positive when modulo is applied to them:
    trace(-1 % 7); // -1
    trace(-2 % 7); // -2
    // …
    trace(-6 % 7); // -6
    trace(-7 % 7); // 0
    trace(-8 % 7); // -1

    You would still need an “if” in order to make sure numbers aren’t negative and add 7 if they are.

  • http://www.snorkl.tv/ carl schooff

    Thanks for dropping in Andreas and for pointing that out. I totally didn’t consider that. I updated the post to include this caveat. 

    Best,

    Carl

  • Harry

    Hey Andreas, rather than add 7 you can multiply by -1 to change a negative into a positive (and a positive into a negative!).

    It’s not an if, but you could use the ternary operator to check if it’s positive or not:

    for(var i:int = -100; i<100; i++){
        trace(i + " % 5 = "  + ( (i < 0) ? (i * -1) % 5: (i % 5) ) );
    }

    Outputs:

    -100 % 5 = 0
    -99 % 5 = 4
    -98 % 5 = 3
    -97 % 5 = 2
    //
    //
    //
    96 % 5 = 1
    97 % 5 = 2
    98 % 5 = 3
    99 % 5 = 4

  • Jeffrey Phillips

    Love the tut! To go backwards through the array, you can do this

    day_txt.text = days_array[ (--count < 0) ? ((count += numDays) % numDays) : (count % numDays) ];

  • vitaLee

    var wrapLoop = function(direction:int){
    var i:int=0,
    j:int=0,
    loops:int = 20,
    size:int = 5;
    while(i++ < loops){
    j = (size + (j + direction)) % size;
    trace(j);
    }
    }
    wrapLoop(1);
    wrapLoop(-1);

  • http://www.snorkl.tv/ carl schooff

    thanks. that could be quite a handy utility!

  • X10

     I tried using ‘*-1′ for the reverse, however it doesn’t go backwards, it end up cycling forwards.
    I used ‘+numDays’ to the modulo result to get it to go backwards.

  • http://www.facebook.com/profile.php?id=100000328472517 Alexander Seitz

    I like that nice trick ;-)

    I’m just wondering, what happens if the app using that trick is running for a really long long time… Let’s say it’s an presentation app running in a museum, and a trillion people a klicking this “next” button for over a year.
    Correct me if I’m wrong, but isn’t it possible that the variable “count” hypothetical could then reach the integer limit (2.147.483.647 (2^31-1)) ?

  • http://www.snorkl.tv/ carl schooff

    Hi Alexander. Happy New Year. Thanks for dropping in.

    yes, you make a good point. in a persistant app the possibility of exceeding the integer limit does exist.

blog comments powered by Disqus

Previous post:

Next post: