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:
-
// testing for an even number - if/else
-
var myNum:Number = 6;
-
//
-
if ((myNum % 2) == 0) {
-
trace ("it's even");
-
} else {
-
trace ("it's odd");
-
}
Or, you can condense the if/else blocks into one line using a ternary operator.
-
// testing for an even number - ternary operator
-
var myNum:Number = 6;
-
//
-
((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.
January 14th, 2005 on 9:24 AM
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);
}
January 14th, 2005 on 12:19 PM
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.
October 4th, 2007 on 8:24 AM
Many thanks for this from a grateful noob.
December 11th, 2007 on 11:06 AM
Since 0 and 1 are boolean values, how about just:
( myVar%2 ) ? trace( “it’s odd”) : trace (”it’s even”);