| Package | Top Level |
| Class | public dynamic class Array |
| Inheritance | Array Object |
Array(). Array() can also be
invoked as a function. And, you can use the array access ([]) operator to initialize an array or access the elements of an array.
You can store a wide variety of data types in an array element, including numbers, strings, objects, and even other arrays. You can create a multidimensional array by creating an indexed array and assigning to each of its elements a different indexed array. Such an array is considered multidimensional because it can be used to represent data in a table.
Arrays are sparse arrays meaning there may be an element at index 0 and another at index 5, but nothing in the index positions between those two elements. In such a case, the elements in positions 1 through 4 are undefined, which indicates the absence of an element, not necessarily the presence of an element with the value undefined.
Array assignment is by reference rather than by value: when you assign one array variable to another array variable, both refer to the same array:
var oneArray:Array = new Array("a", "b", "c");
var twoArray:Array = oneArray; // Both array variables refer to the same array.
twoArray[0] = "z";
trace(oneArray); // Output: z,b,c.
The Array class should not be used to create associative arrays, which are different data structures that contain named elements instead of numbered elements. You should use the Object class to create associative arrays (also called hashes). Although ActionScript permits you to create associative arrays using the Array class, you can not use any of the Array class methods or properties.
You can subclass Array and override or add methods; but specify the subclass as dynamic
or you will lose the ability to store data in an array.
| [] (array access), Object class |
| Property | Defined by | ||
|---|---|---|---|
| CASEINSENSITIVE : uint = 1 [static]
In the sorting methods, this constant specifies case-insensitive sorting.
| Array | ||
| DESCENDING : uint = 2 [static]
In the sorting methods, this constant specifies descending sort order.
| Array | ||
| NUMERIC : uint = 16 [static]
In the sorting methods, this constant specifies numeric (instead of
character-string) sorting.
| Array | ||
| RETURNINDEXEDARRAY : uint = 8 [static]
Specifies that a sort returns an array that consistes of array indices as a result of calling
the
sort() or sortOn() method. | Array | ||
| UNIQUESORT : uint = 4 [static]
In the sorting methods, this constant specifies the unique sorting requirement.
| Array | ||
| Property | Defined by | ||
|---|---|---|---|
![]() | constructor : Object
A reference to the class object or constructor function for a given object instance.
| Object | |
| length : uint
A non-negative integer specifying the number of elements in the array.
| Array | ||
![]() | prototype : Object
[static]
A reference to the prototype object of a class or function object.
| Object | |
| Function | Defined by | ||
|---|---|---|---|
|
Lets you create an array of the specified length.
| Array | ||
|
Lets you create an array containing the specified elements.
| Array | ||
|
Concatenates the elements specified in the parameters with the elements in an array and creates a new array.
| Array | ||
|
Executes a test function on each item in the array until reaching an item that returns
false for the specified function. | Array | ||
|
Executes a test function on each item in the array, and constructs a new array for all items that return
true for the specified function. | Array | ||
|
Executes a function on each item in the array.
| Array | ||
![]() |
Indicates whether an object has a specified property defined.
| Object | |
|
Searches for an item in an array using strict equality (
===) and returns the index
position of the item. | Array | ||
![]() |
Indicates whether an instance of the Object class is in the prototype chain of the object specified
as the parameter.
| Object | |
|
Converts the elements in an array to strings, inserts the specified separator between the
elements, concatenates them, and returns the resulting string.
| Array | ||
|
Searches for an item in an array, working backwards from the last item, and returns the index position of the matching item using strict equality (
===). | Array | ||
|
Executes a function on each item in an array, and constructs a new array of items corresponding to the results of the function on each item in the original array.
| Array | ||
|
Removes the last element from an array and returns the value of that element.
| Array | ||
![]() |
Indicates whether the specified property exists and is enumerable.
| Object | |
|
Adds one or more elements to the end of an array and returns the new length of the array.
| Array | ||
|
Reverses the array in place.
| Array | ||
![]() |
Sets the availability of a dynamic property for loop operations.
| Object | |
|
Removes the first element from an array and returns that element.
| Array | ||
|
Returns a new array that consists of a range of elements from the original array, without modifying the original array.
| Array | ||
|
Executes a test function on each item in the array until reaching an item that returns
true for the specified function. | Array | ||
|
Sorts the elements in an array.
| Array | ||
|
Sorts the elements in an array according to one or more fields in the array.
| Array | ||
|
Adds elements to and removes elements from an array.
| Array | ||
|
Returns a string value representing the elements in the specified array object.
| Array | ||
|
Returns a string value representing the elements in the specified Array object.
| Array | ||
|
Adds one or more elements to the beginning of an array and returns the new length of the array.
| Array | ||
![]() |
Returns the primitive value of the specified object.
| Object | |
public static const CASEINSENSITIVE:uint = 1
options parameter in the sort() or sortOn() method.
The value of this constant is 1.
See also| Array.sort(), Array.sortOn() |
public static const DESCENDING:uint = 2
options parameter in the sort()
or sortOn() method.
The value of this constant is 2.
See also| Array.sort(), Array.sortOn() |
public static const NUMERIC:uint = 16
options
parameter causes the sort() and sortOn() methods
to sort numbers as numeric values, not as strings of numeric characters.
Without the NUMERIC constant, sorting treats each array element as a
character string and produces the results in Unicode order.
For example, given the Array of values [2005, 7, 35], if the NUMERIC
constant is not included in the options parameter, the
sorted Array is [2005, 35, 7], but if the NUMERIC constant is included,
the sorted Array is [7, 35, 2005].
Note that this constant only applies to numbers in the array; it does not apply to strings that contain numeric data (such as ["23", "5"]).
The value of this constant is 16.
See also| Array.sort(), Array.sortOn() |
public static const RETURNINDEXEDARRAY:uint = 8
sort() or sortOn() method. You can use this constant
for the options parameter in the sort() or sortOn()
method, so you have access to multiple views on the array elements while the original array is unmodified.
The value of this constant is 8.
See also| Array.sort(), Array.sortOn() |
public static const UNIQUESORT:uint = 4
sort() or sortOn()
methods. The unique sorting option aborts the sort if any two elements
or fields being sorted have identical values.
The value of this constant is 4.
See also| Array.sort(), Array.sortOn() |
length:uint [read-write]my_array[index] = value), if index is a number, and index+1 is greater than the length property, the length property is updated to index+1.
Note: If you assign a value to the length property that is shorter than the existing length, the array will be truncated.
public function get length():uint
public function set length(value:uint):void
names with the string element Bill.
It then uses the push() method to add another string element Kyle. The length of the array, as
determined by the length property, was one element before the use of push() and is two
elements after the push() is called. Another string, Jeff,
is added to make the length of names three elements. The shift() method is then called twice
to remove Bill and Kyle, making the final array length one.
var names:Array = new Array("Bill");
names.push("Kyle");
trace(names.length); // 2
names.push("Jeff");
trace(names.length); // 3
names.shift();
names.shift();
trace(names.length); // 1
public function Array(numElements:int = 0)
length number of elements.
Parameters
numElements:int (default = 0) — An integer that specifies the number of elements in the array.
|
myArr with no arguments
and an initial length of 0:
package {
import flash.display.Sprite;
public class ArrayExample extends Sprite {
public function ArrayExample() {
var myArr:Array = new Array();
trace(myArr.length); // 0
}
}
}
one, and adds the string element six to the end
of the array using the push() method:
package {
import flash.display.Sprite;
public class ArrayExample extends Sprite {
public function ArrayExample() {
var myArr:Array = new Array(5);
trace(myArr.length); // 5
myArr[0] = "one";
myArr.push("six");
trace(myArr); // one,,,,,six
trace(myArr.length); // 6
}
}
}
toString()
method within the trace() method. This is normally not necessary as trace()
usually converts all objects to strings, although in certain instances, it calls valueOf() on the
object instead.
RangeError — If the sole argument is a number that is not an integer greater than or equal to zero.
|
| [] array access, Array.length |
public function Array(... values)
... values — A comma separated list of one or more arbitrary values.
Note: If only a single numeric parameter is passed to the Array constructor,
it is assumed to specify the array's |
one, two, and three,
and then converts the elements to a string.
package {
import flash.display.Sprite;
public class ArrayExample extends Sprite {
public function ArrayExample() {
var myArr:Array = new Array("one", "two", "three");
trace(myArr.length); // 3
trace(myArr); // one,two,three
}
}
}
RangeError — If the sole argument is a number that is not an integer greater than or equal to zero.
|
| [] array access, Array.length |
public function concat(... args):Array
... args — A value of any data type (such as numbers, elements, or strings) to be concatenated in a new array. If you don't
pass any values, the new array is a duplicate of the original array.
|
Array —
An array that contains the elements from this array followed by elements from
the parameters.
|
numbers, which contains the number elements 1, 2, and 3. letters, which contains the letters a, b, and c. numbersAndLetters, which calls the concat() method to produce the array [1,2,3,a,b,c]. lettersAndNumbers, which calls the concat() method to produce the array [a,b,c,1,2,3].
var numbers:Array = new Array(1, 2, 3);
var letters:Array = new Array("a", "b", "c");
var numbersAndLetters:Array = numbers.concat(letters);
var lettersAndNumbers:Array = letters.concat(numbers);
trace(numbers); // 1,2,3
trace(letters); // a,b,c
trace(numbersAndLetters); // 1,2,3,a,b,c
trace(lettersAndNumbers); // a,b,c,1,2,3
public function every(callback:Function, thisObject:* = null):Boolean
false for the specified function. You use this method to see if all items in an array meet a certain criteria (such as all have values less than some number).
Parameters
callback:Function — The function to run on each item in the array. This function can contain a simple comparison (item < 20) or a more complex operation and can be invoked with three arguments: the value of
an item, the index of an item, and the Array object as in (item, index, array).
|
|
thisObject:* (default = null) — An object to use as this for the function.
|
Boolean —
A Boolean value; true if all items in the array return true for the specified function, otherwise false.
|
package {
import flash.display.Sprite;
public class Array_every extends Sprite {
public function Array_every() {
var arr1:Array = new Array(1, 2, 4);
var res1:Boolean = arr1.every(isNumeric);
trace("isNumeric:", res1); // true
var arr2:Array = new Array(1, 2, "ham");
var res2:Boolean = arr2.every(isNumeric);
trace("isNumeric:", res2); // false
}
private function isNumeric(element:*, index:int, arr:Array):Boolean {
return (element is Number);
}
}
}
| Array.some() |
public function filter(callback:Function, thisObject:* = null):Array
true for the specified function. If an item returns false, it is not included in the new array.
Parameters
callback:Function — The function to run on each item in the array. This function can contain a simple comparison (item < 20) or a more complex operation and will be invoked with three arguments, including the
value of an item, the index of an item, and the Array object as in:
function callback(item:*, index:int, array:Array):void; |
|
thisObject:* (default = null) — An object to use as this for the function.
|
Array —
A new array containing all items from the original array that returned true.
|
package {
import flash.display.Sprite;
public class Array_filter extends Sprite {
public function Array_filter() {
var employees:Array = new Array();
employees.push({name:"Employee 1", manager:false});
employees.push({name:"Employee 2", manager:true});
employees.push({name:"Employee 3", manager:false});
trace("Employees:");
employees.forEach(traceEmployee);
var managers:Array = employees.filter(isManager);
trace("Managers:");
managers.forEach(traceEmployee);
}
private function isManager(element:*, index:int, arr:Array):Boolean {
return (element.manager == true);
}
private function traceEmployee(element:*, index:int, arr:Array):void {
trace("\t" + element.name + ((element.manager) ? " (manager)" : ""));
}
}
}
| Array.map() |
public function forEach(callback:Function, thisObject:* = null):void
callback:Function — The function to run on each item in the array. This function can contain a simple command
(like a trace() statement) or a more complex operation and will be invoked with three arguments,
including the value of an item, the index of an item, and the Array object as in:
function callback(item:*, index:int, array:Array):void; |
|
thisObject:* (default = null) — An object to use as this for the function.
|
traceEmployee() function on each item in the array:
package {
import flash.display.Sprite;
public class Array_forEach extends Sprite {
public function Array_forEach() {
var employees:Array = new Array();
employees.push({name:"Employee 1", manager:false});
employees.push({name:"Employee 2", manager:true});
employees.push({name:"Employee 3", manager:false});
trace(employees);
employees.forEach(traceEmployee);
}
private function traceEmployee(element:*, index:int, arr:Array):void {
trace(element.name + " (" + element.manager + ")");
}
}
}
traceEmployee() function on each item in the array:
package {
import flash.display.Sprite;
public class Array_forEach2 extends Sprite {
public function Array_forEach2() {
var employeeXML:XML = <employees>
<employee name="Steven" manager="false" />
<employee name="Bruce" manager="true" />
<employee name="Rob" manager="false" />
</employees>;
var employeesList:XMLList = employeeXML.employee;
var employeesArray:Array = new Array();
for each (var tempXML:XML in employeesList) {
employeesArray.push(tempXML);
}
employeesArray.sortOn("@name");
employeesArray.forEach(traceEmployee);
}
private function traceEmployee(element:*, index:Number, arr:Array):void {
trace(element.@name + ((element.@manager == "true") ? " (manager)" : ""));
}
}
}
public function indexOf(searchElement:*, fromIndex:int = 0):int
===) and returns the index
position of the item.
Parameters
searchElement:* — The item to find in the array.
|
|
fromIndex:int (default = 0) — The location within the array to start searching for the item.
|
int —
A zero-based index position of the item in the array. If the searchElement argument
is not found the return value will be -1.
|
package {
import flash.display.Sprite;
public class Array_indexOf extends Sprite {
public function Array_indexOf() {
var arr:Array = new Array(123,45,6789);
arr.push("123-45-6789");
arr.push("987-65-4321");
var index:int = arr.indexOf("123");
trace(index); // -1
var index2:int = arr.indexOf(123);
trace(index2); // 0
}
}
}
| Array.lastIndexOf(), === (strict equality) |
public function join(sep:*):String
join() method.
Parameters
sep:* — A character or String that separates array elements in
the returned string. If you omit this parameter, a comma (,) is used as the default
separator.
|
String —
A String consisting of the elements of an array
converted to Strings and separated by the specified parameter.
|
myArr with elements one,
two, and three and then a string containing one and two and three
using the join() method.
var myArr:Array = new Array("one", "two", "three");
var myStr:String = myArr.join(" and ");
trace(myArr); // one,two,three
trace(myStr); // one and two and three
specialChars with elements (,
), -, and a blank space and then a string containing (888) 867-5309.
Then, using a for loop, it removes each type of special character listed in specialChars to
produce a string (myStr) that has only the digits of the phone number remaining: 888675309.
Note that other characters, such as +, could have been added to specialChars and then this
routine would work with international phone number formats.
var phoneString:String = "(888) 867-5309";
var specialChars:Array = new Array("(", ")", "-", " ");
var myStr:String = phoneString;
var ln:uint = specialChars.length;
for(var i:uint; i < ln; i++) {
myStr = myStr.split(specialChars[i]).join("");
}
var phoneNumber:Number = new Number(myStr);
trace(phoneString); // (888) 867-5309
trace(phoneNumber); // 8888675309
| String.split() |
public function lastIndexOf(searchElement:*, fromIndex:int = 0x7fffffff):int
===).
Parameters
searchElement:* — The item to find in the array.
|
|
fromIndex:int (default = 0x7fffffff) — The location within the array to start searching for the item. The default is the maximum
value allowed for an index. If fromIndex is not specified, the search starts at the last item
in the array.
|
int —
A zero-based index position of the item in the array. If the searchElement argument is
not found the return value will be -1.
|
package {
import flash.display.Sprite;
public class Array_lastIndexOf extends Sprite {
public function Array_lastIndexOf() {
var arr:Array = new Array(123,45,6789,123,984,323,123,32);
var index:int = arr.indexOf(123);
trace(index); // 0
var index2:int = arr.lastIndexOf(123);
trace(index2); // 6
}
}
}
| Array.indexOf(), === (strict equality) |
public function map(callback:Function, thisObject:* = null):Array
callback:Function — The function to run on each item in the array. This function can contain a simple command (such as changing the case of an array of strings) or a more complex operation and will be invoked with three arguments,
including the value of an item, the index of an item, and the Array object as in:
function callback(item:*, index:int, array:Array):void; |
|
thisObject:* (default = null) — An object to use as this for the function.
|
Array —
A new array containing the results of the function on each item in the original array.
|
package {
import flash.display.Sprite;
public class Array_map extends Sprite {
public function Array_map() {
var arr:Array = new Array("one", "two", "Three");
trace(arr); // one,two,Three
var upperArr:Array = arr.map(toUpper);
trace(upperArr); // ONE,TWO,THREE
}
private function toUpper(element:*, index:int, arr:Array):String {
return String(element).toUpperCase();
}
}
}
| Array.filter() |
public function pop():Object
Object —
The value of the last element (of any data type) in the specified array.
|
letters with elements a,
b, and c and then the last element (c) is removed from the array using the
pop() method and assigned to the String object letter.
var letters:Array = new Array("a", "b", "c");
trace(letters); // a,b,c
var letter:String = letters.pop();
trace(letters); // a,b
trace(letter); // c
| Array.push(), Array.shift(), Array.unshift() |
public function push(... args):uint
... args — One or more values to append to the array.
|
uint —
An integer representing the length of the new array.
|
letters and then the array
is populated with elements a, b, and c
using the push() method.
var letters:Array = new Array();
letters.push("a");
letters.push("b");
letters.push("c");
trace(letters.toString()); // a,b,c
letters, which is initially
populated with the element a, and then the push() method
is used once to add the elements b, and c to the end of the array,
which is three elements after the push.
var letters:Array = new Array("a");
var count:uint = letters.push("b", "c");
trace(letters); // a,b,c
trace(count); // 3
| Array.pop(), Array.shift(), Array.unshift() |
public function reverse():Array
Array —
The new array.
|
letters with elements a,
b, and c and then the order of the array elements is reversed using the
reverse() method to produce the array [c,b,a].
var letters:Array = new Array("a", "b", "c");
trace(letters); // a,b,c
letters.reverse();
trace(letters); // c,b,a
public function shift():Object
Object —
The first element (of any data type) in an array.
|
letters with elements a,
b, and c and then the method shift() is used to remove the first
element (a) from letters and assign it to the string firstLetter.
var letters:Array = new Array("a", "b", "c");
var firstLetter:String = letters.shift();
trace(letters); // b,c
trace(firstLetter); // a
| Array.pop(), Array.push(), Array.unshift() |
public function slice(startIndex:int = 0, endIndex:int = -1):Array
startIndex element and all elements up to, but not including, the endIndex element.
If you don't pass any parameters, a duplicate of the original array is created.
ParametersstartIndex:int (default = 0) — A number specifying the index of the starting point
for the slice. If start is a negative number, the starting
point begins at the end of the array, where -1 is the last element.
|
|
endIndex:int (default = -1) — A number specifying the index of the ending point for
the slice. If you omit this parameter, the slice includes all elements from the
starting point to the end of the array. If end is a negative
number, the ending point is specified from the end of the array, where -1 is the
last element.
|
Array —
An array that consists of a range of elements from the original array.
|
letters with elements
[a,b,c,d,e,f] and then the array someLetters is created by calling the
slice() method on elements one (b) through three (d),
resulting in an array with elements b and c.
var letters:Array = new Array("a", "b", "c", "d", "e", "f");
var someLetters:Array = letters.slice(1,3);
trace(letters); // a,b,c,d,e,f
trace(someLetters); // b,c
letters with elements
[a,b,c,d,e,f] and then the array someLetters is created by calling the
slice() method on element two (c), resulting in an array with elements
[c,d,e,f].
var letters:Array = new Array("a", "b", "c", "d", "e", "f");
var someLetters:Array = letters.slice(2);
trace(letters); // a,b,c,d,e,f
trace(someLetters); // c,d,e,f
letters with elements
[a,b,c,d,e,f] and then the array someLetters is created by calling the
slice() method on the second to last element from the end (e), resulting
in an array with elements e and f.
var letters:Array = new Array("a", "b", "c", "d", "e", "f");
var someLetters:Array = letters.slice(-2);
trace(letters); // a,b,c,d,e,f
trace(someLetters); // e,f
public function some(callback:Function, thisObject:* = null):Boolean
true for the specified function. You use this method to see if any items in an array meet a certain criteria (such as having a value less than some number).
Parameters
callback:Function — The function to run on each item in the array. This function can contain a simple comparison (item < 20) or a more complex operation and will be invoked with three arguments, including the
value of an item, the index of an item, and the Array object as in:
function callback(item:*, index:int, array:Array):void; |
|
thisObject:* (default = null) — An object to use as this for the function.
|
Boolean —
A Boolean value; true if any items in the array return true for the specified function, otherwise false.
|
package {
import flash.display.Sprite;
public class Array_some extends Sprite {
public function Array_some() {
var arr:Array = new Array();
arr[0] = "one";
arr[1] = "two";
arr[3] = "four";
var isUndef:Boolean = arr.some(isUndefined);
if (isUndef) {
trace("array contains undefined values: " + arr);
} else {
trace("array contains no undefined values.");
}
}
private function isUndefined(element:*, index:int, arr:Array):Boolean {
return (element == undefined);
}
}
}
| Array.every() |
public function sort(... args):Array
By default, Array.sort() works as described in the following list:
If you want to sort an array by using settings that deviate from the default settings,
you can either use one of the sorting options described in the ...args parameter entry
for the sortOptions argument or you can create your own custom function to do the sorting.
If you create a custom function, you can use it by calling the sort() method, using the name
of your custom function as the first argument (compareFunction)
... args — The arguments specifying a comparison function and one or more values that determine the behavior of the sort.
This method uses the syntax and argument order
Note: |
Array —
The return value depends on whether you pass any arguments, as described in
the following list:
|
vegetables with elements
[spinach, green pepper, cilantro, onion, and avocado] and then the array is sorted using
the sort() method, which is called with no parameters. The result is vegetables sorted in
alphabetic order ([avocado, cilantro, green pepper, onion, spinach]).
var vegetables:Array = new Array("spinach",
"green pepper",
"cilantro",
"onion",
"avocado");
trace(vegetables); // spinach,green pepper,cilantro,onion,avocado
vegetables.sort();
trace(vegetables); // avocado,cilantro,green pepper,onion,spinach
vegetables with elements
[spinach, green pepper, Cilantro, Onion, and Avocado] and then the array is sorted using
the sort() method, which is called with no parameters the first time, resulting in the array sorted in
the following order: [Avocado,Cilantro,Onion,green pepper,spinach]. Then sort() is called on
vegetables again using the CASEINSENSITIVE constant as a parameter.
The result is vegetables sorted in alphabetic order
([Avocado, Cilantro, green pepper, Onion, spinach]).
var vegetables:Array = new Array("spinach",
"green pepper",
"Cilantro",
"Onion",
"Avocado");
vegetables.sort();
trace(vegetables); // Avocado,Cilantro,Onion,green pepper,spinach
vegetables.sort(Array.CASEINSENSITIVE);
trace(vegetables); // Avocado,Cilantro,green pepper,Onion,spinach
vegetables and then the
the array is populated using five calls to push(). Each time push() is
called, a new Vegetable object is created by calling the Vegetable()
constructor, which accepts a String (name) and Number (price) object.
The result of calling push() five times with the values shown results in the following
array [lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44]. The
sort() method is then used to sort the array, resulting in the array
[asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44].
var vegetables:Array = new Array();
vegetables.push(new Vegetable("lettuce", 1.49));
vegetables.push(new Vegetable("spinach", 1.89));
vegetables.push(new Vegetable("asparagus", 3.99));
vegetables.push(new Vegetable("celery", 1.29));
vegetables.push(new Vegetable("squash", 1.44));
trace(vegetables);
// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44
vegetables.sort();
trace(vegetables);
// asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44
class Vegetable {
private var name:String;
private var price:Number;
public function Vegetable(name:String, price:Number) {
this.name = name;
this.price = price;
}
public function toString():String {
return " " + name + ":" + price;
}
}
sort() method as is, it is used with a custom sort function
(sortOnPrice), which sorts based on price instead of alphabetically. Note the
new function getPrice() extracts the price.
var vegetables:Array = new Array();
vegetables.push(new Vegetable("lettuce", 1.49));
vegetables.push(new Vegetable("spinach", 1.89));
vegetables.push(new Vegetable("asparagus", 3.99));
vegetables.push(new Vegetable("celery", 1.29));
vegetables.push(new Vegetable("squash", 1.44));
trace(vegetables);
// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44
vegetables.sort(sortOnPrice);
trace(vegetables);
// celery:1.29, squash:1.44, lettuce:1.49, spinach:1.89, asparagus:3.99
function sortOnPrice(a:Vegetable, b:Vegetable):Number {
var aPrice:Number = a.getPrice();
var bPrice:Number = b.getPrice();
if(aPrice > bPrice) {
return 1;
} else if(aPrice < bPrice) {
return -1;
} else if(aPrice == bPrice) {
return 0;
}
}
class Vegetable {
private var name:String;
private var price:Number;
public function Vegetable(name:String, price:Number) {
this.name = name;
this.price = price;
}
public function getPrice():Number {
return price;
}
public function toString():String {
return " " + name + ":" + price;
}
}
numbers with elements
[3,5,100,34,10]. A call to sort() without any parameters will sort
alphabetically, producing the un-desired result [10,100,3,34,5]. To properly
sort numeric values, you must pass the constant NUMERIC to the sort()
method, which will sort numbers as follows: [3,5,10,34,100].
Note: the default behavior of the sort function is to handle each entity as a string.
Array.NUMERIC argument does not actually "convert" other data types to Numbers, it will
simply "allow" the sort algorithm to recognize Numbers as Numbers.
var numbers:Array = new Array(3,5,100,34,10); trace(numbers); // 3,5,100,34,10 numbers.sort(); trace(numbers); // 10,100,3,34,5 numbers.sort(Array.NUMERIC); trace(numbers); // 3,5,10,34,100
| | (bitwise OR), Array.sortOn() |
public function sortOn(fieldName:Object, options:Object = null):Array
If you pass multiple fieldName parameters, the first field represents the primary sort field, the second represents the next sort field, and so on. Flash sorts according to Unicode values. (ASCII is a subset of Unicode.) If either of the elements being compared does not contain the field that is specified in the fieldName parameter, the field is assumed to be undefined, and the elements are placed consecutively in the sorted array in no particular order.
By default, Array.sortOn() works in the following way:
Flash Player 7 added the options parameter, which you can use to override the default sort behavior. To sort a simple array (for example, an array with only one field), or to specify a sort order that the options parameter doesn't support, use Array.sort().
To pass multiple flags, separate them with the bitwise OR (|) operator:
my_array.sortOn(someFieldName, Array.DESCENDING | Array.NUMERIC);
Flash Player 8 added the ability to specify a different sorting option for each field when you sort by more than one field. In Flash Player 8, the options parameter accepts an array of sort options such that each sort option corresponds to a sort field in the fieldName parameter. The following example sorts the primary sort field, a, using a descending sort; the secondary sort field, b, using a numeric sort; and the tertiary sort field, c, using a case-insensitive sort:
Array.sortOn (["a", "b", "c"], [Array.DESCENDING, Array.NUMERIC, Array.CASEINSENSITIVE]);
Note: The fieldName and options arrays must have the same number of elements; otherwise, the options array is ignored. Also, the Array.UNIQUESORT and Array.RETURNINDEXEDARRAY options can be used only as the first element in the array; otherwise, they are ignored.
fieldName:Object — A string that identifies a field to be used as the sort value, or an
array in which the first element represents the primary sort field, the second represents
the secondary sort field, and so on.
|
|
options:Object (default = null) — One or more numbers or names of defined constants, separated by the bitwise OR (|) operator, that change the sorting behavior. The following values are acceptable for the options parameter:
Code hinting is enabled if you use the string form of the flag (for example, |
Array —
The return value depends on whether you pass any parameters:
|
vegetables and then the
the array is populated using five calls to push(). Each time push() is
called, a new Vegetable object is created by calling the Vegetable()
constructor, which accepts a String (name) and Number (price) object.
The result of calling push() five times with the values shown results in the following
array [lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44]. The
sortOn() method is then used with parameter name to produce the following array:
[asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44]. Then the
sortOn() is called again with the parameters price, and the constants
NUMERIC and DESCENDING to produce an array sorted using numbers in descending order:
[asparagus:3.99, spinach:1.89, lettuce:1.49, squash:1.44, celery:1.29]
var vegetables:Array = new Array();
vegetables.push(new Vegetable("lettuce", 1.49));
vegetables.push(new Vegetable("spinach", 1.89));
vegetables.push(new Vegetable("asparagus", 3.99));
vegetables.push(new Vegetable("celery", 1.29));
vegetables.push(new Vegetable("squash", 1.44));
trace(vegetables);
// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44
vegetables.sortOn("name");
trace(vegetables);
// asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44
vegetables.sortOn("price", Array.NUMERIC | Array.DESCENDING);
trace(vegetables);
// asparagus:3.99, spinach:1.89, lettuce:1.49, squash:1.44, celery:1.29
class Vegetable {
public var name:String;
public var price:Number;
public function Vegetable(name:String, price:Number) {
this.name = name;
this.price = price;
}
public function toString():String {
return " " + name + ":" + price;
}
}
records and then the
the array is populated using three calls to push(). Each time push() is
called, the strings name and city and a zip number are
added to records. There are three for loops used to print the array elements. The
first for loop prints the elements in the order they were added. The second for loop is run after
records has been sorted by name and then city using the
sortOn() method. The third for loop produces a different output as records
is re-sorted by city then name.
var records:Array = new Array();
records.push({name:"john", city:"omaha", zip:68144});
records.push({name:"john", city:"kansas city", zip:72345});
records.push({name:"bob", city:"omaha", zip:94010});
for(var i:uint = 0; i < records.length; i++) {
trace(records[i].name + ", " + records[i].city);
}
// Results:
// john, omaha
// john, kansas city
// bob, omaha
trace("records.sortOn('name', 'city');");
records.sortOn(["name", "city"]);
for(var i:uint = 0; i < records.length; i++) {
trace(records[i].name + ", " + records[i].city);
}
// Results:
// bob, omaha
// john, kansas city
// john, omaha
trace("records.sortOn('city', 'name');");
records.sortOn(["city", "name"]);
for(var i:uint = 0; i < records.length; i++) {
trace(records[i].name + ", " + records[i].city);
}
// Results:
// john, kansas city
// bob, omaha
// john, omaha
users and then the
the array is populated using four calls to push(). Each time push() is
called, a User object is created with the User() constructor and a name
string and age uint are added to users. The resulting array set is as follows:
[Bob:3,barb:35,abcd:3,catchy:4].
The array is then sorted in the following ways:
name only, producing the array [Bob:3,abcd:3,barb:35,catchy:4]name and using the CASEINSENSITIVE constant,
producing the array [abcd:3,barb:35,Bob:3,catchy:4]name and using the CASEINSENSITIVE and DESCENDING constants,
producing the array [catchy:4,Bob:3,barb:35,abcd:3]age only, producing the array [abcd:3,Bob:3,barb:35,catchy:4]age and using the NUMERIC constant,
producing the array [Bob:3,abcd:3,catchy:4,barb:35]age and using the DESCENDING and NUMERIC constants,
producing the array [barb:35,catchy:4,Bob:3,abcd:3]Then an array called indicies is created and assigned the results of a sort
by age and using the NUMERIC and RETURNINDEXEDARRAY constants,
resulting in the array [Bob:3,abcd:3,catchy:4,barb:35], which is then printed out
using a for loop.
class User {
public var name:String;
public var age:Number;
public function User(name:String, age:uint) {
this.name = name;
this.age = age;
}
public function toString():String {
return this.name + ":" + this.age;
}
}
var users:Array = new Array();
users.push(new User("Bob", 3));
users.push(new User("barb", 35));
users.push(new User("abcd", 3));
users.push(new User("catchy", 4));
trace(users); // Bob:3,barb:35,abcd:3,catchy:4
users.sortOn("name");
trace(users); // Bob:3,abcd:3,barb:35,catchy:4
users.sortOn("name", Array.CASEINSENSITIVE);
trace(users); // abcd:3,barb:35,Bob:3,catchy:4
users.sortOn("name", Array.CASEINSENSITIVE | Array.DESCENDING);
trace(users); // catchy:4,Bob:3,barb:35,abcd:3
users.sortOn("age");
trace(users); // abcd:3,Bob:3,barb:35,catchy:4
users.sortOn("age", Array.NUMERIC);
trace(users); // Bob:3,abcd:3,catchy:4,barb:35
users.sortOn("age", Array.DESCENDING | Array.NUMERIC);
trace(users); // barb:35,catchy:4,Bob:3,abcd:3
var indices:Array = users.sortOn("age", Array.NUMERIC | Array.RETURNINDEXEDARRAY);
var index:uint;
for(var i:uint = 0; i < indices.length; i++) {
index = indices[i];
trace(users[index].name, ": " + users[index].age);
}
// Results:
// Bob : 3
// abcd : 3
// catchy : 4
// barb : 35
| | (bitwise OR), Array.sort() |
public function splice(startIndex:int, deleteCount:uint, ... values):Array
Note: To override this method in a subclass of Array, use ...args for the parameters.
For example:
public override function splice(...args) {
// your statements here
}
Parameters
startIndex:int — An integer that specifies the index of the element in the array where the insertion or
deletion begins. You can specify a negative integer to specify a position relative to the end of the array
(for example, -1 is the last element of the array).
|
|
deleteCount:uint — An integer that specifies the number of elements to be deleted. This number includes the
element specified in the startIndex parameter. If no value is specified for the
deleteCount parameter, the method deletes all of the values from the startIndex
element to the last element in the array. If the value is 0, no elements are deleted.
|
|
... values — An optional list of one or more comma separated values, or an array,
to insert into the array at the insertion point specified in the startIndex parameter.
|
Array —
An array containing the elements that were removed from the original array.
|
vegetables with elements
[spinach, green pepper, cilantro, onion, and avocado] and then the splice()
method is called with the parameters 2 and 2, which assigns
cilantro and onion to the array spliced and
vegetables then contains [spinach,green pepper,avocado]. Then
splice() is called a second time using parameters 1, 0,
and the array spliced to assign
[spinach,cilantro,onion,green pepper,avocado] to vegetables.
var vegetables:Array = new Array("spinach",
"green pepper",
"cilantro",
"onion",
"avocado");
var spliced:Array = vegetables.splice(2, 2);
trace(vegetables); // spinach,green pepper,avocado
trace(spliced); // cilantro,onion
vegetables.splice(1, 0, spliced);
trace(vegetables); // spinach,cilantro,onion,green pepper,avocado
public function toLocaleString():String
Array.toString() method.
Returns
String —
A string.
|
| Array.toString() |
public function toString():String
Array.join() method.
Returns
String —
A string.
|
toString method.
The toString method is automatically called by the trace function
but is being called explicitly here to show its use.
var vegetables:Array = new Array();
vegetables.push("lettuce");
vegetables.push("spinach");
vegetables.push("asparagus");
vegetables.push("celery");
vegetables.push("squash");
trace(vegetables.toString());
// lettuce,spinach,asparagus,celery,squash
| String.split(), Array.join() |
public function unshift(... args):uint
... args — One or more numbers, elements, or variables to be inserted at the beginning of the array.
|
uint —
An integer representing the new length of the array.
|
names and then adds
the strings Bill and Jeff are added using push()
and then the strings Alfred and Kyle are added to the beginning of
names using the unshift() method two times.
var names:Array = new Array();
names.push("Bill");
names.push("Jeff");
trace(names); // Bill,Jeff
names.unshift("Alfred");
names.unshift("Kyle");
trace(names); // Kyle,Alfred,Bill,Jeff
| Array.pop(), Array.push(), Array.shift() |
myArr with no arguments
and an initial length of 0:
package {
import flash.display.Sprite;
public class ArrayExample extends Sprite {
public function ArrayExample() {
var myArr:Array = new Array();
trace(myArr.length); // 0
}
}
}