Recipe 1.10.
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 14
for details on working with dates):
// Check if today is April 17th.
var current:Date = new Date( );
if (current.getDate( ) == 17 && current.getMonth( ) == 3) {
trace ("Happy Birthday, Bruce!");
}
You can add extra
parentheses to make the logic
more apparent:
// Check if today is April 17th.
if ((current.getDate( ) == 17) && (current.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 ((current.getDay( ) == 0) || (current.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 (!(userName == "Bruce")) {
trace ("This application knows only Bruce's birthday.");
}
The preceding example could be rewritten using
the inequality operator, !=:
if (userName != "Bruce") {
trace ("This application knows only Bruce's birthday.");
}
Any Boolean value, or an expression that
converts to a Boolean, can be
used as the test condition:
// Check to see if a sprite is visible. If so, display a
// message. This condition is shorthand for _sprite.visible == true
if (_sprite.visible) {
trace("The sprite is visible.");
}
The logical NOT operator is often used to
check if something is false instead of true:
// Check to see if a sprite is invisible (not visible). If so,
// display a message. This condition is shorthand for
// _sprite.visible != true or _sprite.visible == false.
if (!_sprite.visible) {
trace("The sprite is invisible. Set it to visible before trying this action.");
}
The logical NOT operator is often used in
compound conditions along with the logical OR operator:
// Check to see if the name is neither Bruce nor Joey. (This could
// also be rewritten using two inequality operators and a logical
// AND.)
if (!((userName == "Bruce") || (userName == "Joey"))) {
trace ("Sorry, but only Bruce and Joey have access to this application.");
}
ActionScript doesn't bother to evaluate the
second half of a logical AND statement unless the first half
of the expression is true. If the first half is
false, the overall expression is always false, so
it would be inefficient to bother evaluating the second half.
Likewise, ActionScript does not bother to evaluate the second half
of a logical OR statement unless the first half of the
expression is false. If the first half is TRue,
the overall expression is
always true.
|