Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Syntax and Language Fundamentals > About statements > About conditions > Using the if..else statement | |||
The if..else conditional statement lets you test a condition and then execute a block of code if that condition exists or execute an alternative block of code if the condition does not exist.
For example, the following code tests whether the value of x exceeds 20, generates a trace() statement if it does, or generates a different trace() statement if it does not:
if (x > 20) {
trace("x is > 20");
} else {
trace("x is <= 20");
}
If you do not want to execute an alternative block of code, you can use the if statement without the else statement.
The if..else statement in Flash is similar to the if statement. For example, if you use the if statement to validate that a user's supplied user name and password matches a value stored in a database, then you might want to redirect the user based on whether the user name and password are correct. If the login is valid, you can redirect the user to a welcome page using the if block. However, if the login was invalid, you can redirect the user to the login form and display an error message using the else block.
To use an if..else statement in a document:
// create a string that holds AM/PM based on the time of day.
var amPm:String;
// no parameters pass to Date, so returns current date/time.
var current_date:Date = new Date();
// if current hour is greater than/equal to 12, sets amPm string to "PM".
if (current_date.getHours() >= 12) {
amPm = "PM";
} else {
amPm = "AM";
}
trace(amPm);
In this code, you create a string that holds AM or PM based on the current time of day. If the current hour is greater than or equal to 12, the amPM string sets to PM. Finally, you trace the amPm string, and if the hour is greater than or equal to 12, PM is displayed. Otherwise, you'll see AM in the Output panel.
|
|
|
|