Recipe 5.7. Converting an Array to a String


Problem

You want to convert an array to a string.

Solution

Use the join( ) method.

Discussion

ActionScript provides you with a built-in way to quickly convert arrays to strings (assuming, of course, that the array elements themselves are either strings or another datatype that ActionScript can automatically cast to a string) using the join( ) method. You should pass the join( ) method a string that tells Flash which delimiter to use to join the elements:

var letters:Array = ["a", "b", "c"]; trace(letters.join("|"));   // Displays: a|b|c

If you don't provide a delimiter, Flash uses a comma by default:

var letters:Array = ["a", "b", "c"]; trace(letters.join());   // Displays: a,b,c

The toString( ) method does the same thing as the join( ) method either with no parameters or with the comma as the parameter. In fact, if you try to use an array in a situation in which a string is required, Flash automatically calls the toString( ) method, as follows:

var letters:Array = ["a", "b", "c"]; trace(letters);  // Displays: a,b,c


See Also

Recipe 5.6




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

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