
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
160
|
Chapter 7: Conditionals
} else {
trace("x and y are equal");
}
// Expanded Nested if/else chain
if (x > y) {
trace("x is larger than y");
} else {
if (x < y) {
trace("x is smaller than y");
} else {
trace("x and y are equal");
}
}
The switch Statement
The switch statement, introduced in Flash Player 6, lets us execute one (or some-
times more) of several possible code blocks, based on the value of a single test
expression. In some cases, the switch statement is easier to write and more legible
than an if statement. For example, in the following switch statement, we greet the
user with a custom message depending on the value of the test expression
gender:
var surname = "Porter";
var gender = "male";
switch (gender) {
case "femaleMarried":
trace("Hello Mrs. " + surname);
break;
case "femaleGeneric":
trace("Hello Ms. " + surname);
break;
case "male":
trace("Hello Mr. " + surname);
break;
default:
trace("Hello " + surname);
}
Our switch statement attempts to match the value of gender to one of the supplied
case expressions: “femaleMarried”, “femaleGeneric”, or “male”. Because
gender
matches the expression “male”, the substatement trace("Hello Mr. " + surname); is
executed. If the test expression had not matched any case clause, then the default
statement—trace("Hello" + surname);—would have ...