[ Team LiB ] |
Recipe 1.3 Performing Actions Conditionally1.3.1 ProblemYou want to perform an action only when a condition is true. 1.3.2 SolutionUse an if statement or a switch statement. 1.3.3 DiscussionYou often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute an action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :). The conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situation. The if statement is most appropriate when you want to tell your Flash movie to do something only when a certain condition is met (i.e., when the condition is true). When you have several possible conditions to test, you can use the switch statement instead. And you can use Flash's ternary conditional operator to perform conditional checking and assignment on a single line. First, we'll look at the if statement. Of the conditional statements in ActionScript, the if statement is the most important to understand. In its most basic form, an if statement includes the keyword if followed by the test expression whose truthfulness you want to evaluate to determine which action or actions to execute. The test expression must be in parentheses, and the statement(s) to be executed should be within curly braces (the latter is mandatory if there is more than one statement in the statement block). Here, we check whether animalName contains the word "turtle". This might be used to check whether the user answered a quiz question correctly (here, animalName is a variable assumed to contain the user's answer). Note that the double equals sign (==) is used to test whether two items are equal. It should not be confused with the single equals sign (=), which is used to assign a value to an item. if (animalName == "turtle") { // This trace( ) statement executes only when animalName is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); } Additionally, you can add an else clause to an if statement to perform alternative actions if the condition is false. Note that the trace( ) command has no effect when the Flash movie is running in a browser, so it is intended for testing purposes only. We use the gotoAndStop( ) command to jump to a different frame (presumably one that displays an appropriate message) depending on whether the user answered the question correctly or incorrectly. if (animalName == "turtle") { // These statements execute only when animalName is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); gotoAndStop("CongratulationsScreen"); } else { // These statements execute only when animalName is not equal to "turtle". trace("Sorry, you got the question wrong."); gotoAndStop("TryAgainScreen"); }
You can add an else if clause to an if statement. If the if condition is true, the else if clause is skipped. If the if condition is false, the ActionScript interpreter checks to see if the else if condition is true. if (animalName == "turtle") { // This trace( ) statement executes only when animalName is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); } else if (animalName == "dove") { // This trace( ) statement executes only when animalName is not "turtle" but is // "dove". trace("Sorry, a dove is a bird, not a reptile."); } What if the preceding example was written as two separate if statements (one to check if animalName is "turtle" and another to check if it is "dove")? The example would work as intended, but it would be less efficient. Using the else if statement guarantees that if animalName is "turtle", we don't bother checking if it is also equal to "dove".
When you use an if statement with both else if and else clauses, the else clause must be the last clause in the statement. The final else clause is convenient as a catchall; it's where you can put statements that take the appropriate action if none of the other conditions are met. if (animalName == "turtle") { // This trace( ) statement executes only when animalName is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); } else if (animalName == "dove") { // This statement executes only when animalName is not "turtle" but is "dove". trace("Sorry, a dove is a bird, not a reptile."); } else { // This statement executes only when animalName is neither "turtle" nor "dove". trace("Sorry, try again."); } You can also include more than one else if clause in an if statement. However, in that case, you should most likely use a switch statement instead; generally, switch statements are more legible and succinct than the comparable if statement. Where performance is critical, some ActionScripters prefer to use if statements, which allow somewhat greater control for optimization purposes. A switch statement is composed of three parts:
The switch keyword is always followed by the test expression in parentheses. Then, the switch statement body is enclosed in curly braces. There can be one or more case statements within the switch statement body. Each case (other than the default case) starts with the case keyword followed by the case expression and a colon. The default case (if one is included) starts with the default keyword followed by a colon. Therefore, the general form of a switch statement is: switch (testExpression) { case caseExpression: // case body case caseExpression: // case body default: // case body } Here is an example. Note that once a case tests true, all the remaining actions in all subsequent cases within the switch statement body also execute. This example is most likely not what the programmer intended: var animalName = "dove"; /* In the following switch statement, the first trace( ) statement does not execute because animalName is not equal to "turtle". But both the second and third trace( ) statements execute, because once the "dove" case tests true, all subsequent code is executed. */ switch (animalName) { case "turtle": trace("Yay! 'Turtle' is the correct answer."); case "dove": trace("Sorry, a dove is a bird, not a reptile."); default: trace("Sorry, try again."); } Normally, you should use break statements at the end of each case body to exit the switch statement after executing the actions under the matching case.
You don't need to add a break statement to the end of the last case or default clause, since it is the end of the switch statement anyway: var animalName = "dove"; // Now, only the second trace( ) statement executes. switch (animalName) { case "turtle": trace("Yay! 'Turtle' is the correct answer."); break; case "dove": trace("Sorry, a dove is a bird, not a reptile."); break; default: trace("Sorry, try again."); } The switch statement is especially useful when you want to perform the same action for one of several matching possibilities. Simply list multiple case expressions one after the other. For example: switch (animalName) { case "turtle": case "alligator": case "iguana": trace("Yay! You named a reptile."); break; case "dove": case "pigeon": case "cardinal": trace("Sorry, you specified a bird, not a reptile."); break; default: trace("Sorry, try again."); } ActionScript also supports the ternary conditional operator (? :), which allows you to perform a conditional test and an assignment statement on a single line. A "ternary" operator requires three operands, as opposed to the one or two operands required by unary and binary operators. The first operand of the conditional operator is a conditional expression that evaluates to true or false. The second operand is the value to assign to the variable if the condition is true, and the third operand is the value to assign if the condition is false. varName = (conditional expression) ? valueIfTrue : valueIfFalse; One common use of the ternary operator is in assigning default values to variables in functions if a parameter value was omitted when calling the function. For example: function myFunction (param) { var val = (param != undefined) ? param : "default value"; } The preceding example can be written using an if statement: function myFunction (param) { var val; if (param != undefined) { val = param; } else { val = "default value"; } } Either way is correct; however, the ternary operator requires fewer lines of code and executes faster. Here is an example in which salutation defaults to "Hello" if no greeting was specified; otherwise, salutation is set to greeting's value. function welcome (greeting) { var salutation = (greeting != undefined) ? greeting: "Hello"; trace (salutation + " Sailor!") } Here are some examples of the results: welcome( ); // Displays: Hello Sailor! welcome("Ahoy"); // Displays: Ahoy Sailor! |
[ Team LiB ] |