Simulating the switch Statement
Though switch
statements (sometimes called
case statements) are not supported by
ActionScript, this common form of complex conditional can be
emulated. A switch statement lets us execute
only one of a series of possible code blocks based on the value of a
single test expression. For example, in the following
JavaScript 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" :
alert("Hello Mrs. " + surname);
break;
case "femaleGeneric" :
alert("Hello Ms. " + surname);
break;
case "male" :
alert("Hello Mr. " + surname);
break;
default :
alert("Hello " + surname);
}In the JavaScript example, switch attempts to
match the value of gender to one of the
case expressions: “femaleMarried”,
“femaleGeneric”, or “male”. Because
gender matches the expression “male”,
the substatement alert(“Hello Mr. " + surname);
is executed. If the test expression had not matched any case, then
the default statement—alert(“Hello " +
surname);—would have been executed.
In ActionScript, we can simulate a
switch statement using a chain of
if-else
if-else statements, like this:
var surname = "Porter"; var gender = "male"; if (gender == "femaleMarried") { trace("Hello Mrs. " + surname); } else if (gender == "femaleGeneric") { trace("Hello Ms. " + surname); } else if (gender == "male") { trace("Hello Mr. " + surname); } else { trace("Hello " + surname); ...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