ActionScript 3.0 Cookbook: Chapter 1: ActionScript Basics
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

To determine if a number is invalid, use the special isNaN( ) function, as follows:

var quantity:Number = 15 - "rabbits";
if (isNaN(quantity)) {
  trace("Sorry, that is not a valid number.");
}

To test the opposite of a condition (i.e., whether a condition is not true) use the logical NOT operator (!). For example, to check whether a variable contains a valid number, use !isNAN( ), as follows:

var quantity:Number = 15 - "rabbits";
if (!isNaN(quantity)) {

  // The number is not invalid, so it must be a valid number
  trace ("That is a valid number.");
}

Of course, you can perform comparisons using the well-known comparison operators. For example, you can use the < and > operators to check if one value is less than or greater than another value:

trace(5 < 6);    // Displays: true
trace(5 > 5);    // Displays: false

Similarly, you can use the <= and >= operators to check if one value is less than or equal to, or greater than or equal to, another value:

trace(5 <= 6);   // Displays: true
trace(5 >= 5);   // Displays: true

You should also be aware that ActionScript compares datatypes differently. ActionScript datatypes can be categorized either as primitive (string, number, and Boolean) or composite (object, sprite, and array). When you compare primitive datatypes, ActionScript compares them "by value." In this example, quantity and total are considered equal because they both contain the value 6:

var quantity:Number = 6;
var total:Number = 6;
trace (quantity == total);         // Displays: true

However, when you compare composite datatypes, ActionScript compares them "by reference." Comparing items by reference means that the two items are considered equal only if both point to exactly the same object, not merely objects with matching contents. For example, two arrays containing exactly the same values are not considered equal:

// Create two arrays with the same elements.
var arrayOne:Array = new Array("a", "b", "c");
var arrayTwo:Array = new Array("a", "b", "c");
trace(arrayOne == arrayTwo);          // Displays: false

Two composite items are equal only if they both refer to the identical object, array, or sprite. For example:

// Create a single array
var arrayOne:Array = new Array("a", "b", "c");
// Create another variable that references the same array.
var arrayTwo:Array = arrayOne;
trace(arrayOne == arrayTwo);          // Displays: true

See Also

Recipe 5.8

Section 1.9: Performing Actions Conditionally

Problem

You want to perform some action only when a condition is true.

Solution

Use an if or a switch statement.

Discussion

You often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute some action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :).

Conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situation. For example, the if statement is most appropriate when you want to tell a Flash movie to do something only when a certain condition is met (e.g., 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 let's 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 for the trace( ) command to have any effect, the .swf must be compiled using Debug, and not Run, mode. Make a call to a method named showMessage( ) that displays an appropriate message depending on whether the user got the answer right or wrong:

if (animalName == "turtle") {
  // These statements execute only when animalName is equal 
  // to "turtle".
  showMessage("Yay! 'Turtle' is the correct answer.");
}
else {
  // These statements execute only when animalName is not equal 
  // to "turtle".
  showMessage("Sorry, you got the question wrong.");  
}

For testing purposes, you can create a showMessage( ) method that traces out the string sent to it. In a real-world example, you might want to display this message in a text field, or display it to the user some other way, such as in a dialog box.


This excerpt is from ActionScript 3.0 Cookbook. Well before Ajax and Windows Presentation Foundation, Macromedia Flash provided the first method for building "rich" web pages. Now, Adobe is making Flash a full-fledged development environment, and learning ActionScript 3.0 is key. That's a challenge for even the most experienced Flash developer. This Cookbook offers more than 300 solutions to solve a wide range of coding dilemmas, so you can learn to work with the new version right away.

buy button

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".
  showMessage ("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
  // This trace( ) statement executes only when animalName is not 
  // "turtle", but is "dove".
  showMessage ("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."

If your two conditions are mutually exclusive, use an else if clause to check the second condition. If your two conditions are not mutually exclusive, and you want to perform both statement blocks when both conditions are met, use two separate if statements.

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".
  showMessage ("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
   // This statement executes only when animalName is not 
   // "turtle", but is "dove".
  showMessage ("Sorry, a dove is a bird, not a reptile.");
}
else {
  // This statement executes only when animalName is neither 
  // "turtle" nor "dove".
  showMessage ("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
Every switch statement must begin with the switch keyword.
Test expression
An expression, enclosed in parentheses, whose value you want to test to determine which action or actions to execute.
The switch statement body
The statement body, enclosed in curly braces, is composed of cases. Each case is made up of the following parts:
The case or default keyword
A case must begin with a case keyword. The exception is the default case (analogous to an else clause in an if statement), which uses the default keyword.
Case expression
An expression, whose value is to be compared to the switch statement's test expression. If the two values are equal, the code in the case body is executed. The default case (the case that uses the default keyword) does not need a case expression.
Case body
One or more statements, usually ending in a break statement, to be performed if that case is true.

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Next Pagearrow