joshbuhler.com

ActionScript testing for even number

by Josh on Jan.14, 2005, under ActionScript, Flash

Not much in today's post. I was checking my web stats last night, and the search terms "actionscript testing for even number" showed up in the top ten searches from Google. I haven't posted on this, so I don't know how I got these search terms in my logs ( I once got "deep frying turkeys"), but as a service to whoever was looking for that, here you go:

  1. // testing for an even number - if/else
  2. var myNum:Number = 6;
  3. //
  4. if ((myNum % 2) == 0) {
  5.         trace ("it's even");
  6. } else {
  7.         trace ("it's odd");
  8. }

Or, you can condense the if/else blocks into one line using a ternary operator.

  1. // testing for an even number - ternary operator
  2. var myNum:Number = 6;
  3. //
  4. ((myNum % 2) == 0) ? trace ("it's even") : trace ("it's odd");

Just copy and paste the code above to try it out, replacing myNum with any number. The trick here is the modulo operator (%). It returns the remainder of the first item divided by the second. If there is no remainder when your first number is divided by two, then you have an even number.

The modulo is actually pretty handy. It can be used in the situation above, when trying to find an even number, but I've also used it in a music application to build a metronome and determine the different beats of a measure.

This is old news to a lot of developers out there, but sometimes it's nice to throw something out there for the n00bs as well. We all were once.



:, , ,
4 comments for this entry:
  1. Patrick Bateman

    If that code snipped is supposed to be for noobies, what the heck are you using the ternary operator for?

    How about an AS1 func:

    isEven(num) {
    return (num%2==0);
    }

  2. Josh

    Good point. I learned how to use ternary operator in the first Flash class I took, and have been doing it ever since. Just a force of habit I guess. I’ve since updated the code sample to show a simpler version.

  3. Tim

    Many thanks for this from a grateful noob.

  4. rdas7

    Since 0 and 1 are boolean values, how about just:

    ( myVar%2 ) ? trace( “it’s odd”) : trace (”it’s even”);

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...