146 Syntax and Language Fundamentals
Using the if..else if statement
You can test for more than one condition using the if..else if conditional statement. You
use the following syntax in an
if..else if statement:
// else-if statement
if (condition) {
// statements;
} else if (condition) {
// statements;
} else {
// statements;
}
You want to use an if..else if block in your Flash projects when you need to check a series
of conditions. For example, if you want to display a different image on the screen based on the
time of the day the user is visiting, you can create a series of
if statements that determine if it’s
early morning, afternoon, evening, or night time. Then you can display an appropriate
graphic.
The following code not only tests whether the value of
x exceeds 20 but also tests whether the
value of
x is negative:
if (x > 20) {
trace("x is > 20");
} else if (x < 0) {
trace("x is negative");
}
To use an if..else if statement in a document:
1. Select File > New and then select Flash Document.
2. Select Frame 1 of the Timeline, and then type the following ActionScript in the
Actions panel:
var now_date:Date = new Date();
var currentHour:Number = now_date.getHours();
// if the current hour is less than 11AM...
if (currentHour < 11) {
trace("Good morning");
// else..if the current hour is less than 3PM...
} else if (currentHour < 15) {
trace("Good afternoon");
// else..if the current hour is less than 8PM...
} else if (currentHour < 20) {
trace("Good evening");
// else the current hour is between 8PM and 11:59PM
} else {
trace("Good night");
}