User Guide

Indexed arrays 235
Querying an array
The remaining four methods of the Array class—concat(), join(), slice(),
toString()—all query the array for information, but do not modify the array. The
concat() and slice() methods both return new arrays, while the join() and toString()
methods both return strings. The
concat() method takes a new array or list of elements as
arguments and combines it with the existing array to create a new array. The
slice() method
has two parameters, aptly named
startIndex and an endIndex, and returns a new array
containing a copy of the elements “sliced” from the existing array. The slice begins with the
element at
startIndex and ends with the element just before endIndex. That bears
repeating: the element at
endIndex is not included in the return value.
The following example uses
concat() and slice() to create new arrays using elements of
other arrays:
var array1:Array = ["alpha", "beta"];
var array2:Array = array1.concat("gamma", "delta");
trace(array2); // output: alpha,beta,gamma,delta
var array3:Array = array1.concat(array2);
trace(array3); // output: alpha,beta,alpha,beta,gamma,delta
var array4:Array = array3.slice(2,5);
trace(array4); // output: alpha,beta,gamma
You can use the join() and toString() methods to query the array and return its contents
as a string. If no parameters are used for the
join() method, the two methods behave
identically—they return a string containing a comma-delimited list of all elements in the
array. The
join() method, unlike the toString() method, accepts a parameter named
delimiter, which allows you to choose the symbol to use as a separator between each element
in the returned string.
The following example creates an array called
rivers and calls both join() and toString()
to return the values in the array as a string. The
toString() method is used to return
comma-separated values (
riverCSV), while the join() method is used to return values
separated by the
+ character.
var rivers:Array = ["Nile", "Amazon", "Yangtze", "Mississippi"];
var riverCSV:String = rivers.toString();
trace(riverCSV); // output: Nile,Amazon,Yangtze,Mississippi
var riverPSV:String = rivers.join("+");
trace(riverPSV); // output: Nile+Amazon+Yangtze+Mississippi