Book HomeActionScript: The Definitive GuideSearch this book

7.4. 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);
}

In a more advanced approach, we could simulate a switch as a series of functions stored in the properties of a generic object. Example 7-1 shows the technique. Pay close attention to the comments to learn how it works. Also note the use of the conditional operator, which we encountered earlier.

Example 7-1. A Simulated switch Statement

var surname = "Porter"; // Our user's name
var gender = "male";    // Our user's gender (the test expression)

// Create an object to act as our simulated switch statement
var mySwitch = new Object( );

// Assign "case expression" properties to the mySwitch object.
// Each "case expression" property holds a function.
mySwitch.femaleMarried = function( ) {
  trace("Hello Mrs. " + surname); 
};
mySwitch.femaleGeneric = function( ) {
  trace("Hello Ms. " + surname); 
};
mySwitch.male = function( ) {
  trace("Hello Mr. " + surname); 
};
mySwitch.default = function( ) {
  trace("Hello " + surname);
};

// Now execute the appropriate function, depending on the
// value of gender (in our case, "male"). If the named
// property doesn't exist, execute the default function instead.
mySwitch[gender] ? mySwitch[gender]() : mySwitch["default"]( );


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.