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 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 datatyping that ActionScript would otherwise perform.
Whenever we use a value in a context that does not match its 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 righthand 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 any 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 internal 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"
converts internally to:
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 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, "Conditionals").
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.
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, non-numeric 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.
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.
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 5 breaks the rules in order to maintain compatibility with Flash 4) |
Empty string ("") |
false |
Array |
true |
Object |
true |
Movieclip |
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.
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"
The String( ) function has the same result as the toString( ) method, but 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 Part III, "Language Reference".
Because the plus operator (+) favors strings in its automatic conversion rules, adding "" to any datum converts that datum to a string.
x + ""; // Convert x to a string 523 + ""; // Convert 523 to the string "523"
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. 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 Part III, "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 and price2, we use:
totalCost = Number(price1) + Number(price2);
Otherwise, price1 and price2 will be concatenated as strings, not added as numbers. For more information on text fields, see Chapter 18, "On-Screen Text Fields".
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
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 non-blank character is a legal numeric character. Otherwise, parseInt( ) yields NaN. The number extracted via parseInt( ) starts with the first non-blank character in the string and ends with the character before either the first non-numeric character or the first occurrence of a decimal point.
Some parseInt( ) examples:
parseInt("1a") // Extracts 1 parseInt("1.3a" // Extracts 1 parseInt(" 1a") // Extracts 1 parseInt("I am 14 years old") // Yields NaN (the first non-blank // character is not a number) parseInt("14 years old") // Extracts 14
The parseFloat( ) function extracts the first floating-point number that appears in a string, provided that the string's first non-blank 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 non-blank character is not a valid numeric character. The number extracted by parseFloat( ) is a series of characters that starts with the first non-blank character in the string and ends with the character before the first non-numeric character (any character other than +, -, 0-9, or a decimal point).
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( ), see Part III, "Language Reference".
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 Part III, "Language Reference".
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 converted to a number trace(typeof x); // Displays: "string"; the conversion was temporary
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 to a number trace(typeof x); // Displays: "number". The conversion was permanent because // it occurred as part of an assignment.
In Flash 4, the string operators and the numeric operators were completely distinct -- one set of operators worked only with numbers, and a second set worked only with strings. For example, the string concatenation operator in Flash 4 was &, but the mathematical addition operator was +. Similarly, string comparisons were done with the eq and ne operators, but numeric comparisons were accomplished via = and <>. Table 3-4 lists the Flash 5 syntax for analogous Flash 4 operators.
Operation |
Flash 4 Syntax |
Flash 5 Syntax |
---|---|---|
String concatenation |
+ or add |
|
String equality |
== |
|
String inequality |
!= |
|
String comparison |
>=, >, <=, < |
|
Numeric addition |
+ |
+ |
Numeric equality |
= |
== |
Numeric inequality |
<> |
!= |
Numeric comparison |
>=, >, <=, < |
>=, >, <=, < |
Some Flash 5 operators can operate on both strings and numbers. For example, when used with strings, the + operator concatenates its operands together to form a new string. But when used with numbers, the + operator adds its two operands together mathematically. Similarly, the equality operator (==) and inequality operator (!=) in Flash 5 are used to compare strings, numbers, and other datatypes.
Because many Flash 5 operators work with multiple datatypes but Flash 4 operators do not, an ambiguity arises when a Flash 4 file is imported into Flash 5. Therefore, when importing Flash 4 files, Flash 5 automatically inserts the Number( ) function around any numeric data that is used as an operand of the following potentially ambiguous operators (unless the operand is a numeric literal):
+, ==, !=, <>, <, >, >=, <=
Flash 4 files converted to Flash 5 will also have the string concatenation operator (&) changed to the new add operator. Table 3-5 contains examples of Flash 4-to-Flash 5 operator translation.
Flash 4 Syntax |
Flash 5 Syntax |
---|---|
Loop While (count <= numRecords) |
while (Number(count)<= Number(numRecords)) |
If (x = 15) |
if(Number(x) == 15) |
If (y <> 20) |
if(Number(y) != 20) |
Set Variable: "lastName" = "kavanagh" |
lastName = "kavanagh" |
Set Variable: "name" = "molly" & lastName |
name = "molly" add lastName |
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-6.
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 identified, we can assign the clips to an array for programmatic handling. (If you can't follow all of Example 3-1, revisit it after completing Part I, "ActionScript Fundamentals".)
var childClip = new Array( ); var childClipCount = 0; for (i in _root) { thisItem = _root[i]; if (typeof thisItem == "movieclip") { // Notice the use of the postfix increment operator childClip[childClipCount++] = thisItem; } } // Now that our array is populated, we can use it // to manipulate the clips it contains childClip[0]._x = 0; // Place the first clip on the left of the Stage childClip[1]._y = 0; // Place the second clip at the top of the Stage
Copyright © 2002 O'Reilly & Associates. All rights reserved.