3.4. Datatype ConversionTake 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. 3.4.1. Automatic Type ConversionWhenever 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. Table 3-1. Converting to a Number
Table 3-2 shows the results of converting each datatype to a string. Table 3-2. Converting to a String
Table 3-3 shows the results of converting each datatype to a Boolean. Table 3-3. Converting to a Boolean
3.4.2. Explicit Type ConversionIf 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( ) methodWe 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( ) functionThe 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". 3.4.2.3. Converting to a string with empty string concatenationBecause 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" 3.4.2.4. Converting to a number with the Number( ) functionJust 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". 3.4.2.5. Converting to a number by subtracting zeroTo 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( ) functionsThe 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". 3.4.2.7. Converting to a BooleanWhen 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". 3.4.3. Conversion DurationAll 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. 3.4.4. Flash 4-to-Flash 5 Datatype ConversionIn 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. Table 3-4. Flash 4 Versus Flash 5 Operators
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. Table 3-5. Sample Flash 4-to-Flash 5 Operator Translations
3.4.5. Determining the Type of an Existing DatumTo 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. Table 3-6. Return Values of typeof
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".) Example 3-1. Populating an Array with Dynamically Identified Movie Clipsvar 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. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|