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); ...
Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.