3.4 Datatype Conversion

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 3.  Data and Datatypes

Take a closer look at the example from the previous section. In that example, each datum "1" and 2 belonged to its own datatype; the first was a string and the second was a number. We saw that the interpreter joined the two values together to form the string "12". Note that the interpreter first had to convert the number 2 into the string "2". Only after that automatic conversion was performed could the value "2" be joined (concatenated) to the string "1".

Datatype conversion simply means changing the type of a datum. Not all datatype conversions are automatic; we may also change a datum's type explicitly in order to override the default datatype conversion that ActionScript would otherwise perform. Explicit conversion is known as typecasting, or simply casting.

3.4.1 Automatic Type Conversion

Whenever we use a value in a context that does not match the expected datatype, the interpreter attempts a conversion. That is, if the interpreter expects data of type A, and we provide data of type B, the interpreter will attempt to convert our type B data into type A data. For example, in the following code we use the string "Flash" as the right-hand operand of the subtraction operator. Since only numbers may be used with the subtraction operator, the interpreter attempts to convert the string "Flash" into a number:

999 - "Flash";

Of course, the string "Flash" can't be successfully converted into a legitimate number, so it is converted into the special numeric data value NaN (i.e., Not-a-Number). NaN is a legal value of the number datatype, intended specifically to handle such a situation. With "Flash" converted to NaN, our expression ends up looking like this to the interpreter (though we never see this interim step):

999 - NaN;

Both operands of the subtraction operator are now numbers, so the operation can proceed: 999 - NaN yields the value NaN, which is the final value of our expression.

An expression that yields the numeric value NaN isn't particularly useful; most conversions have more functional results. For example, if a string contains only numeric characters, it can be converted into a useful number. The expression:

999 - "9";  // The number 999 minus the string "9"

is interpreted as:

999 - 9;    // The number 999 minus the number 9

which yields the value 990 when the expression is resolved. Automatic conversion is most common with the plus operator, the equality operator, the comparison operators, and in conditional or loop statements. In order to be sure of the result of any expression that involves automatic conversion, we have to answer three questions: (a) what is the expected datatype of the current context? (b) what happens when an unexpected datatype is supplied in that context? and (c) when conversion occurs, what is the resulting value?

To answer the first and second questions, we need to consult the appropriate topics elsewhere in this book (e.g., to determine what datatype is expected in a conditional statement, see Chapter 7).

The next three tables, which list the rules of automatic conversion, answer the third question, "When conversion occurs, what is the resulting value?" Table 3-1 shows the results of converting each datatype to a number.

Table 3-1. Converting to a number

Original data

Result after conversion

undefined

0

null

0

Boolean

1 if the original value is true; 0 if the original value is false

Numeric string

Equivalent numeric value if string is composed only of base-10 numbers, whitespace, exponent, decimal point, plus sign, or minus sign (e.g., "-1.485e2")

Other strings

Empty strings, nonnumeric strings, including strings starting with "x", "0x", or "FF", convert to NaN

"Infinity"

Infinity

"-Infinity"

-Infinity

"NaN"

NaN

Array

NaN

Object

The return value of the object's valueOf( ) method

Movieclip

NaN

Table 3-2 shows the results of converting each datatype to a string.

Table 3-2. Converting to a string

Original data

Result after conversion

undefined

"" (the empty string)

null

"null"

Boolean

"true" if the original value was true; "false" if the original value was false.

NaN

"NaN"

0

"0"

Infinity

"Infinity"

-Infinity

"-Infinity"

Other numeric value

String equivalent of the number. For example, 944.345 becomes "944.345".

Array

A comma-separated list of element values.

Object

The value that results from calling toString( ) on the object. By default, the toString( ) method of an object returns "[object Object]". The toString( ) method can be customized to return a more useful result (e.g., toString( )of a Date object returns: "Sun May 14 11:38:10 EDT 2000").

Movieclip

The path to the movie clip instance, given in absolute terms starting with the document level in the Player. For example, "_level0.ball".

Table 3-3 shows the results of converting each datatype to a Boolean.

Table 3-3. Converting to a Boolean

Original data

Result after conversion

undefined

false

null

false

NaN

false

0

false

Infinity

true

-Infinity

true

Other numeric value

true

Nonempty string

true if the string can be converted to a valid nonzero number, false if not; in ECMA-262, a non-empty string always converts to true (Flash diverges from the ECMA standard to maintain compatibility with Flash 4)

Empty string ("")

false

Array

true

Object

true

Movieclip

true

3.4.2 Explicit Type Conversion

If the automatic (implicit) type-conversion rules do not suit our purpose, we can manually (explicitly) change a datum's type. When we take matters into our own hands, we must remember that the rules listed in the preceding tables still apply.

3.4.2.1 Converting to a string with the toString( ) method

We can invoke the toString( )method to convert any datum to a string. For example:

x.toString( );      // Get the string value of the variable x. (523).toString( );  // Returns "523". Note that we use parentheses                     // so that the "." isn't treated as a decimal point.

When we invoke the toString( ) method on a number, we may also provide a numeric argument indicating the base of the number system in which we'd like the converted string to be represented. This provides a handy means of switching between hexadecimal, decimal, and octal numbers. For example:

var myColor = 255; var hexColor = myColor.toString(16);  // Sets hexColor to "ff"
3.4.2.2 Converting to a string with the String( ) function

The String( ) function has the same result as the toString( ) method, but it uses a different grammar:

String(x);    // Convert x to a string String(523);  // Convert 523 to the string "523"

Don't confuse the global String( ) function with the built-in class constructor of the same name. Both are described in the Language Reference.

3.4.2.3 Converting to a string with empty string concatenation

Because the plus operator (+) favors strings in its automatic conversion rules, concatenating the empty string ("") with any datum converts that datum to a string.

// Convert x to a string. x + ""; // Here we check the character position of the number 2 in 523. We first  // concatenate 523 and "", before invoking a String method on the converted value. trace((523 + "").indexOf(2));
3.4.2.4 Converting to a number with the Number( ) function

Just as the String( ) function converts data to the string type, the Number( ) function converts its argument to the number type. When conversion to a real number is impossible or illogical, the Number( ) function returns a special numeric value as described in Table 3-1. Here are some examples:

Number(age);     // Yields the value of age converted to a number Number("29");    // Yields the number 29 Number("sara");  // Yields NaN

Don't confuse the global Number( ) function with the built-in class constructor of the same name. Both are described in the Language Reference.

Because user input in on-screen text fields always belong to the string type, it's necessary to convert text fields to numbers when performing mathematical calculations. For example, if we want to find the sum of the text fields price1_txt and price2_txt, we use:

totalCost = Number(price1_txt.text) + Number(price2_txt.text);

Otherwise, price1_txt and price2_txt will be concatenated as strings, not added as numbers. For more information on text fields, see TextField in the Language Reference.

3.4.2.5 Converting to a number by subtracting zero

To trick the interpreter into converting a datum to a number, we can subtract zero from that datum. Again, the conversion follows the rules described in Table 3-1:

"953" - 0      // Yields 953 "molly" - 0    // Yields NaN x - 0          // Yields the value of x converted to a number
3.4.2.6 Converting to a number using the parseInt( ) and parseFloat( ) functions

The parseInt( ) and parseFloat( ) functions convert a string containing numbers and letters into a number. The parseInt( ) function extracts the first integer that appears in a string, provided that the string's first nonblank character is a legal numeric character. Otherwise, parseInt( ) yields NaN. The number extracted via parseInt( ) starts with the first nonblank character in the string and ends with the character before either the first nonnumeric character or the first occurrence of a decimal point.

Here are some parseInt( ) examples:

parseInt("1a")                 // Yields 1 parseInt("1.3a"                // Yields 1 parseInt("     1a")            // Yields 1 parseInt("I am 14 years old")  // Yields NaN (the first nonblank                                // character is not a number) parseInt("14 years old")       // Yields 14     // Convert decimal to hexadecimal. (255).toString(16);            // Yields: ff // Convert hexadecimal to decimal. parseInt("0xFF");              // Yields 255

The parseFloat( ) function returns the first floating-point number that appears in a string, provided that the string's first nonblank character is a valid numeric character. (A floating-point number is a positive or negative number that contains a decimal value, such as -10.5 or 345.678.) Like parseInt( ), parseFloat( ) yields the special numeric value NaN if the string's first nonblank character is not a valid numeric character. The number extracted by parseFloat( ) is the numeric conversion of the series of characters that starts with the first nonblank character in the string and ends with the character before the first nonnumeric character (any character other than +, -, 0-9, a decimal point, or an e or E when used for exponential notation).

Here are some parseFloat( ) examples:

parseFloat("1.3a");             // Extracts 1.3 parseFloat("2.75 years old")    // Extracts 2.75 parseFloat("1nce upon a time")  // Extracts 1 parseFloat("I'm 3.5 feet tall") // Yields NaN

For more information on parseInt( ) and parseFloat( ) including how to specify a radix to convert between number systems see the ActionScript Language Reference.

3.4.2.7 Converting to a Boolean

When we want to convert a datum to a Boolean, we can use the global Boolean( ) function, which uses similar syntax to the String( ) and Number( ) functions. For example:

Boolean(5);  // The result is true Boolean(x);  // Converts value of x to a Boolean

Don't confuse the global Boolean( ) function with the built-in class constructor of the same name. Both are described in the Language Reference.

3.4.3 Conversion Duration

All type conversions performed on variables, array elements, and object properties are temporary unless the conversion happens as part of an assignment. Here we see a temporary conversion:

var x = "10";     // x is a string. y = x - 5;        // y is now 5; x's value was temporarily converted to a number. trace(typeof x);  // Displays: "string"; the conversion was temporary because                    // it occurred incidentally while evaluating an expression.

Here we see a permanent conversion that is the result of an assignment:

x = "10";         // x is a string. x = x - 5;        // x is converted permanently to a number. trace(typeof x);  // Displays: "number"; the conversion was permanent because                   // it occurred as part of an assignment.

3.4.4 Determining the Type of an Existing Datum

To determine what kind of data is held in a given expression before, say, proceeding with a section of code, we use the typeof operator, as follows:

typeof expression;

The typeof operator returns a string telling us the datatype of expression, according to Table 3-4.

Table 3-4. Return values of typeof

Original datatype

typeof return value

Number

"number"

String

"string"

Boolean

"boolean"

Object

"object"

Array

"object"

null

"null"

Movieclip

"movieclip"

Function

"function"

undefined

"undefined"

Here are a few examples:

trace(typeof "game over");    // Displays: "string" in the Output window var x = 5; trace(typeof x);              // Displays: "number" var now = new Date(); trace(typeof now);            // Displays: "object"

As shown in Example 3-1, when combined with a for-in statement, typeof provides a handy way to find all the movie clip instances on a timeline. Once the clips are identified, we can assign them to an array for programmatic handling. (If you can't follow all of Example 3-1, revisit it after completing Part I.)

Example 3-1. Populating an array with dynamically identified movie clips
// Create an array in which to store the clips. var childClips = new Array( );   // Check all the properties of the main timeline. for (prop in _root) {   // If the current property is a movie clip...   if (typeof _root[prop] =  = "movieclip") {     // ...add it to the clips array.     childClips.push(_root[prop]);   } }     // Now that our array is populated, we can use it to manipulate the clips it contains. childClips[0]._x = 0;  // Place the first clip on the left of the Stage. childClips[1]._y = 0;  // Place the second clip at the top of the Stage. 
     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net