1.4. Performing Complex Conditional Testing
Problem
You want to make a decision based on multiple conditions.
Solution
Use the logical AND
(&&), OR
(||), and NOT
(!) operators to create compound
conditional statements.
Discussion
Many statements in ActionScript can involve conditional expressions,
including if, while, and
for statements, and statements using the ternary
conditional operator. To test whether two conditions are both true,
use the logical AND operator
(&&), as follows (see Chapter 10 for details on working with dates):
// Check if today is April 17th.
now = new Date( );
if (now.getDate() == 17 && now.getMonth( ) == 3) {
trace ("Happy Birthday, Bruce!");
}You can add extra parentheses to make the logic more apparent:
// Check if today is April 17th.
if ((now.getDate() == 17) && (now.getMonth( ) == 3)) {
trace ("Happy Birthday, Bruce!");
}Here we use the logical OR operator
(||) to test whether either condition is true:
// Check if it is a weekend.
if ((now.getDay() == 0) || (now.getDay( ) == 6) ) {
trace ("Why are you working on a weekend?");
}You can also use a logical NOT operator (!) to check if a condition is not true:
// Check to see if the name is not Bruce.
if (!(name == "Bruce")) {
trace ("This application knows only Bruce's birthday.");
}The preceding example could be rewritten using the inequality
operator (!=):
if (name != "Bruce") {
trace ("This application knows only Bruce's birthday.");
}Any Boolean value, or an expression that converts to a Boolean, can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access