Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Syntax and Language Fundamentals > About statements > About conditions > 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:
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");
}
In this code, you create a string called currentHour that holds the current hour number (for example, if it's 6:19 pm, currentHour holds the number 18). You use the getHours() method of the Date class to get the current hour. Then you can use the if..else if statement to trace information to the Output panel, based on the number that returns. For more information, see the comments in the previous code snippet.
|
|
|
|