144 Syntax and Language Fundamentals
Using the if statement
Use the if statement when you want to execute a series of statements based on a whether a
certain condition is true.
// if statement
if (condition) {
// statements;
}
There are several times when you’ll use if statements when you work on a Flash project. For
example, if you are building a Flash site that requires users to log in before they can access
certain sections of a website, you can use an
if statement to validate that the user enters some
text in the username and password fields.
If you need to validate user names and passwords using an external database, you probably
want to verify that the username/password combination a user submits matches a record in
the database. You also want to check whether the user has permission to access the specified
part of the site.
If you script animations in Flash, you might want to use the
if statement to test whether an
instance on the Stage is still within the boundaries of the Stage. For example, if a ball moves
downward along the y-axis, you might need to detect when the ball collides with the bottom
edge of the Stage, so you can change the direction so that the ball appears to bounce upwards.
To use an if statement:
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:
// create a string to hold AM and PM
var amPm:String = "AM";
// 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";
}
trace(amPm);
3.
Select Control > Test Movie to test the ActionScript.
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.