Querying an array

Four methods of the Array and Vector classes— concat() , join() , slice() , and 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

One issue to be aware of with the join() method is that any nested Array or Vector instances are always returned with comma-separated values, no matter what separator you specify for the main array elements, as the following example shows:

var nested:Array = ["b","c","d"]; 
var letters:Array = ["a",nested,"e"];  
var joined:String = letters.join("+"); 
trace(joined); // output: a+b,c,d+e