
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
54
|
Chapter 3: Datatypes and Type Checking
if (msg instanceof Array) {
var arr:Array = Array(msg); // Cast to Array here
trace(arr.join("\n"));
}
}
Unfortunately, due to the existence of the global Array( ) function, the would-be
cast in the preceding code actually converts the existing array in
msg to a new, single-
element array, which is stored in
arr. If we test the function as follows:
output([1, 2, 3]);
the Output panel displays:
1,2,3
Notice that there’s no newline character between elements because the entire array
passed to output( ) is now the first and only element in
arr!
To fix the problem, we’re forced to operate on
msg directly, without first casting it to
Array, as indicated in bold:
function output (msg:Object):Void {
// Use typeof to detect the datatype of primitive values.
if (typeof msg == "string") {
trace(msg);
}
// Use instanceof to check the class of an object.
if (msg instanceof Array) {
trace(msg.join("\n")); // No cast here.
}
}
With our revised version of output( ), the following test:
output([1, 2, 3]);
causes the Output panel to display the desired result (each element on its own line):
1
2
3
Datatype Information for Built-in Classes
When working with static typing and ActionScript 2.0’s built-in classes, you must
observe the declared datatypes for each class. For ...