• Like
Array properties
Upcoming SlideShare
Loading in...5
×

Array properties

  • 400 views
Uploaded on

 

More in: Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
400
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
7
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. ArrayPackage Top LevelClass public dynamic class ArrayInheritance Array Object Language ActionScript 3.0 Version: Runtime Flash Player 9, AIR 1.0 Versions: The Array class lets you access and manipulate arrays. Array indices are zero-based, which means that the first element in the array is [0], the second element is [1], and so on. To create an Array object, you use the new Array() constructor . Array() can also be invoked as a function. In addition, 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 might 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. Do not use the Array class to create associative arrays (also called hashes), which are data structures that contain named elements instead of numbered elements. To create associative arrays, use the Object class. Although ActionScript permits you to create associative arrays using the Array class, you cannot use any of the Array class methods or properties with associative arrays. You can extend the Array class and override or add methods. However, you must specify the subclass as dynamic or you will lose the ability to store data in an array. View the examples
  • 2. See also[] (array access)Object classPublic Properties Show Inherited Public Properties Property length : uint A non-negative integer specifying the number of elements in the array.Public Methods Show Inherited Public Methods MethodArray(numElements:int = 0) Lets you create an array of the specified number of elements.Array(... values) Lets you create an array that contains the specified elements.concat(... args):Array Concatenates the elements specified in the parameters with the elements in an array and creates a new array.every(callback:Function, thisObject:* = null):Boolean Executes a test function on each item in the array until an item is reached that returns false for the specified function.filter(callback:Function, thisObject:* = null):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.forEach(callback:Function, thisObject:* = null):void
  • 3. Executes a function on each item in the array.indexOf(searchElement:*, fromIndex:int = 0):int Searches for an item in an array by using strict equality (===) and returns the index position of the item.join(sep:*):String Converts the elements in an array to strings, inserts the specified separator between the elements, concatenates them, and returns thlastIndexOf(searchElement:*, fromIndex:int = 0x7fffffff):int Searches for an item in an array, working backward from the last item, and returns the index position of the matching item using stmap(callback:Function, thisObject:* = null):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 eapop():* Removes the last element from an array and returns the value of that element.push(... args):uint Adds one or more elements to the end of an array and returns the new length of the array.reverse():Array Reverses the array in place.shift():* Removes the first element from an array and returns that element.slice(startIndex:int = 0, endIndex:int = 16777215):Array Returns a new array that consists of a range of elements from the original array, without modifying the original array.
  • 4. some(callback:Function, thisObject:* = null):Boolean Executes a test function on each item in the array until an item is reached that returns true.sort(... args):Array Sorts the elements in an array.sortOn(fieldName:Object, options:Object = null):Array Sorts the elements in an array according to one or more fields in the array.splice(startIndex:int, deleteCount:uint, ... values):Array Adds elements to and removes elements from an array.toLocaleString():String Returns a string that represents the elements in the specified array.toString():String Returns a string that represents the elements in the specified array.unshift(... args):uint Adds one or more elements to the beginning of an array and returns the new length of the array.Public Constants Constant CASEINSENSITIVE : uint = 1 [static] Specifies case-insensitive sorting for the Array class sorting methods. DESCENDING : uint = 2 [static] Specifies descending sorting for the Array class sorting methods.
  • 5. NUMERIC : uint = 16 [static] Specifies numeric (instead of character-string) sorting for the Array class sorting methods. RETURNINDEXEDARRAY : uint = 8 [static] Specifies that a sort returns an array that consists of array indices. UNIQUESORT : uint = 4 [static] Specifies the unique sorting requirement for the Array class sorting methods.Property Detail length propertylength:uintLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:A non-negative integer specifying the number of elements in the array. This property is automaticallyupdated when new elements are added to the array. When you assign a value to an array element (forexample,my_array[index] = value), if index is a number, and index+1 is greater thanthe 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 willbe truncated.Implementation public function get length():uint public function set length(value:uint):voidExample ( How to use this example )The following code creates an Array object names with the string element Bill. It then usesthe push() method to add another string element Kyle. The length of the array, as determined bythe length property, was one element before the use of push() and is two elements after push() iscalled. Another string, Jeff, is added to make the length of names three elements. The shift() methodis then called twice to removeBill and Kyle, making the final array of length one.var names:Array = new Array("Bill");names.push("Kyle");trace(names.length); // 2
  • 6. names.push("Jeff");trace(names.length); // 3names.shift();names.shift();trace(names.length); // 1Constructor Detail ( Array ) Constructorpublic function Array(numElements:int = 0)Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Lets you create an array of the specified number of elements. If you dont specify any parameters, anarray containing 0 elements is created. If you specify a number of elements, an array is createdwith numElementsnumber of elements.Note: This class shows two constructor method entries because the constructor accepts variable types ofarguments. The constructor behaves differently depending on the type and number of arguments passed,as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.ParametersnumElements:int (default = 0) — An integer that specifies the number of elements in thearray.Throws RangeError — The argument is a number that is not an integer greater than or equal to 0.See also[] array accessArray.lengthExample ( How to use this example )The following example creates the Array object myArr with no arguments and an initial length of 0:package { import flash.display.Sprite; public class Array_Array extends Sprite {
  • 7. public function Array_Array() { var myArr:Array = new Array(); trace(myArr.length); // 0 } }}The following example creates an Array object with 5 initial elements, with a length of 5, and populatesthe first element with the string "one", and adds the string element "six" to the end of the array byusing thepush() method:package { import flash.display.Sprite; public class Array_Array_2 extends Sprite { public function Array_Array_2() { var myArr:Array = new Array(5); trace(myArr.length); // 5 myArr[0] = "one"; myArr.push("six"); trace(myArr); // one,,,,,six trace(myArr.length); // 6 } }} ( Array )Constructorpublic function Array(... values)Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Lets you create an array that contains the specified elements. You can specify values of any type. Thefirst element in an array always has an index (or position) of 0.Note: This class shows two constructor entries because the constructor accepts variable types ofarguments. The constructor behaves differently depending on the type and number of arguments passed,as detailed in each entry. ActionSript 3.0 does not support method or constructor overloading.Parameters... values — A comma-separated list of one or more arbitrary values.
  • 8. Note: If only a single numeric parameter is passed to the Array constructor, it is assumed to specify thearrays length property.Throws RangeError — The argument is a number that is not an integer greater than or equal to 0.See also[] array accessArray.lengthExample ( How to use this example )The following example creates a new Array object with an initial length of 3, populates the array with thestring elements one, two, and three, and then converts the elements to a string.package { import flash.display.Sprite; public class Array_Array_3 extends Sprite { public function Array_Array_3() { var myArr:Array = new Array("one", "two", "three"); trace(myArr.length); // 3 trace(myArr); // one,two,three } }}Method Detail ( concat ) methodAS3 function concat(... args):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Concatenates the elements specified in the parameters with the elements in an array and creates a newarray. If the parameters specify an array, the elements of that array are concatenated.Parameters... args — A value of any data type (such as numbers, elements, or strings) to be concatenated in a new array. If
  • 9. you dont pass any values, the new array is a duplicate of the original array.Returns Array — An array that contains the elements from this array followed by elements from the parameters.Example ( How to use this example )The following code creates four Array objects: • The numbers array, which contains the numbers 1, 2, and 3. • The letters array, which contains the letters a, b, and c. • The numbersAndLetters array, which calls the concat() method to produce the array [1,2,3,a,b,c]. • The lettersAndNumbers array, 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,3trace(letters); // a,b,ctrace(numbersAndLetters); // 1,2,3,a,b,ctrace(lettersAndNumbers); // a,b,c,1,2,3 ( every )methodAS3 function every(callback:Function, thisObject:* = null):BooleanLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Executes a test function on each item in the array until an item is reached that returns false for thespecified function. You use this method to determine whether all items in an array meet a criterion, suchas having values less than a particular number.Parameterscallback:Function — The function to run on each item in the array. This function can contain a simplecomparison (for example, item < 20) or a more complex operation, and is invoked with three arguments; thevalue of an item, the index of an item, and the Array object:function callback(item:*, index:int, array:Array):Boolean;thisObject:* (default = null) — An object to use as this for the function.Returns
  • 10. Boolean — A Boolean value of true if all items in the array return true for the specified function; otherwise, false.See alsoArray.some()Example ( How to use this example )The following example tests two arrays to determine whether every item in each array is a number. Italso outputs the results of the test, showing that isNumeric is true for the first array and false for thesecond: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); } }} ( filter ) methodAS3 function filter(callback:Function, thisObject:* = null):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Executes a test function on each item in the array and constructs a new array for all items thatreturn true for the specified function. If an item returns false, it is not included in the new array.Parameterscallback:Function — The function to run on each item in the array. This function can contain a simplecomparison (for example, item < 20) or a more complex operation, and is invoked with three arguments; the
  • 11. value of an item, the index of an item, and the Array object: function callback(item:*, index:int, array:Array):Boolean;thisObject:* (default = null) — An object to use as this for the function.Returns Array — A new array that contains all items from the original array that returned true.See alsoArray.map()Example ( How to use this example )The following example creates an array of all employees who are managers: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)" : "")); } }} ( forEach )methodAS3 function forEach(callback:Function, thisObject:* = null):voidLanguage ActionScript 3.0
  • 12. Version:Runtime Flash Player 9, AIR 1.0Versions:Executes a function on each item in the array.Parameterscallback:Function — The function to run on each item in the array. This function can contain a simplecommand (for example, a trace() statement) or a more complex operation, and is invoked with three arguments;the value of an item, the index of an item, and the Array object: function callback(item:*, index:int, array:Array):void;thisObject:* (default = null) — An object to use as this for the function.Example ( How to use this example )The following example runs the trace() statement in the traceEmployee() function on each item in thearray: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 + ")"); } }}The following example also runs the trace() statement in a slightly altered traceEmployee() functionon each item in the array:package { import flash.display.Sprite; public class Array_forEach_2 extends Sprite { public function Array_forEach_2() { var employeeXML:XML = <employees> <employee name="Steven" manager="false" />
  • 13. <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)" : "")); } }} ( indexOf )methodAS3 function indexOf(searchElement:*, fromIndex:int = 0):intLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Searches for an item in an array by using strict equality (===) and returns the index position of the item.ParameterssearchElement:* — The item to find in the array.fromIndex:int (default = 0) — The location in the array from which to start searching for theitem.Returns int — A zero-based index position of the item in the array. If the searchElement argument is not found, the return value is -1.See alsoArray.lastIndexOf()=== (strict equality)Example ( How to use this example )The following example displays the position of the specified array:
  • 14. 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 } }} ( join ) methodAS3 function join(sep:*):StringLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Converts the elements in an array to strings, inserts the specified separator between the elements,concatenates them, and returns the resulting string. A nested array is always separated by a comma (,),not by the separator passed to the join() method.Parameterssep:* (default = NaN) — A character or string that separates array elements in the returned string. If you omit thisparameter, a comma is used as the default separator.Returns String — A string consisting of the elements of an array converted to strings and separated by the specified parameter.See alsoString.split()Example ( How to use this example )The following code creates an Array object myArr with elements one, two, and three and then a stringcontaining one and two and three using the join() method.
  • 15. var myArr:Array = new Array("one", "two", "three");var myStr:String = myArr.join(" and ");trace(myArr); // one,two,threetrace(myStr); // one and two and threeThe following code creates an Array object specialChars with elements (, ), -, and a blank space andthen creates a string containing (888) 867-5309. Then, using a for loop, it removes each type ofspecial character listed in specialChars to produce a string (myStr) that contains only the digits of thephone number remaining: 888675309. Note that other characters, such as +, could have been addedto specialCharsand 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-5309trace(phoneNumber); // 8888675309 ( lastIndexOf ) methodAS3 function lastIndexOf(searchElement:*, fromIndex:int = 0x7fffffff):intLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Searches for an item in an array, working backward from the last item, and returns the index position ofthe matching item using strict equality (===).ParameterssearchElement:* — The item to find in the array.fromIndex:int (default = 0x7fffffff) — The location in the array from which to start searching for the item.The default is the maximum value allowed for an index. If you do not specify fromIndex, the search starts at the
  • 16. last item in the array.Returns int — A zero-based index position of the item in the array. If the searchElement argument is not found, the return value is -1.See alsoArray.indexOf()=== (strict equality)Example ( How to use this example )The following example displays the position of the specified array: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 } }} ( map )methodAS3 function map(callback:Function, thisObject:* = null):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Executes a function on each item in an array, and constructs a new array of items corresponding to theresults of the function on each item in the original array.Parameterscallback:Function — The function to run on each item in the array. This function can contain a simplecommand (such as changing the case of an array of strings) or a more complex operation, and is invoked with threearguments; the value of an item, the index of an item, and the Array object: function callback(item:*, index:int, array:Array):void;
  • 17. thisObject:* (default = null) — An object to use as this for the function.Returns Array — A new array that contains the results of the function on each item in the original array.See alsoArray.filter()Example ( How to use this example )The following example changes all items in the array to use uppercase letters: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(); } }} po ( p ) methodAS3 function pop():*Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Removes the last element from an array and returns the value of that element.Returns * — The value of the last element (of any data type) in the specified array.See also
  • 18. Array.push()Array.shift()Array.unshift()Example ( How to use this example )The following code creates an Array object letters with elements a, b, and c. The last element (c) isthen 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,cvar letter:String = letters.pop();trace(letters); // a,btrace(letter); // c ( push ) methodAS3 function push(... args):uintLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Adds one or more elements to the end of an array and returns the new length of the array.Parameters... args — One or more values to append to thearray.Returns uint — An integer representing the length of the new array.See alsoArray.pop()Array.shift()Array.unshift()Example ( How to use this example )The following code creates an empty Array object letters and then populates the array with theelements a, b, and c using the push() method.var letters:Array = new Array();letters.push("a");
  • 19. letters.push("b");letters.push("c");trace(letters.toString()); // a,b,cThe following code creates an Array object letters, which is initially populated with the element a.The push() method is then used once to add the elements b and c to the end of the array, which isthree elements after the push.var letters:Array = new Array("a");var count:uint = letters.push("b", "c");trace(letters); // a,b,ctrace(count); // 3 ( reverse )methodAS3 function reverse():ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Reverses the array in place.Returns Array — The new array.Example ( How to use this example )The following code creates an Array object letters with elements a, b, and c. The order of the arrayelements is then reversed using the reverse() method to produce the array [c,b,a].var letters:Array = new Array("a", "b", "c");trace(letters); // a,b,cletters.reverse();trace(letters); // c,b,a ( shift ) methodAS3 function shift():*Language ActionScript 3.0Version:
  • 20. Runtime Flash Player 9, AIR 1.0Versions:Removes the first element from an array and returns that element. The remaining array elements aremoved from their original position, i, to i-1.Returns * — The first element (of any data type) in an array.See alsoArray.pop()Array.push()Array.unshift()Example ( How to use this example )The following code creates the Array object letters with elements a, b, and c. The shift() method isthen 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,ctrace(firstLetter); // a ( slice ) methodAS3 function slice(startIndex:int = 0, endIndex:int = 16777215):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Returns a new array that consists of a range of elements from the original array, without modifying theoriginal array. The returned array includes the startIndex element and all elements up to, but notincluding, theendIndex element.If you dont 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 startIndex is a negative number, the starting point begins at the end of the array, where -1 is the last element.endIndex:int (default = 16777215) — A number specifying the index of the ending point for the slice. If youomit this parameter, the slice includes all elements from the starting point to the end of the array. IfendIndex is anegative number, the ending point is specified from the end of the array, where -1 is the last element.
  • 21. Returns Array — An array that consists of a range of elements from the original array.Example ( How to use this example )The following code creates an Array object letters with elements [a,b,c,d,e,f]. Thearray someLetters is then 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,ftrace(someLetters); // b,cThe following code creates an Array object letters with elements [a,b,c,d,e,f].Thearray someLetters is then created by calling the slice() method on element two (c), resulting in anarray 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,ftrace(someLetters); // c,d,e,fThe following code creates an Array object letters with elements [a,b,c,d,e,f]. Thearray someLetters is then created by calling the slice() method on the second to last element fromthe 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,ftrace(someLetters); // e,f ( some ) methodAS3 function some(callback:Function, thisObject:* = null):BooleanLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:
  • 22. Executes a test function on each item in the array until an item is reached that returns true. Use thismethod to determine whether any items in an array meet a criterion, such as having a value less than aparticular number.Parameterscallback:Function — The function to run on each item in the array. This function can contain a simplecomparison (for example item < 20) or a more complex operation, and is invoked with three arguments; the valueof an item, the index of an item, and the Array object: function callback(item:*, index:int, array:Array):Boolean;thisObject:* (default = null) — An object to use as this for the function.Returns Boolean — A Boolean value of true if any items in the array return true for the specified function; otherwise false.See alsoevery()Example ( How to use this example )The following example displays which values are undefined: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); } }}
  • 23. ( sort )methodAS3 function sort(... args):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Sorts the elements in an array. This method sorts according to Unicode values. (ASCII is a subset ofUnicode.)By default, Array.sort() works in the following way: • Sorting is case-sensitive (Z precedes a). • Sorting is ascending (a precedes b). • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order. • All elements, regardless of data type, are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".To sort an array by using settings that deviate from the default settings, you can either use one of thesorting options described in the sortOptions portion of the ...args parameter description, or you cancreate your own custom function to do the sorting. If you create a custom function, you callthe sort() method, and use the name of your custom function as the first argument(compareFunction)Parameters... args — The arguments specifying a comparison function and one or more values that determine the behaviorof the sort.This method uses the syntax and argument order Array.sort(compareFunction, sortOptions) with thearguments defined as follows: • compareFunction - A comparison function used to determine the sorting order of elements in an array. This argument is optional. A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value: o A negative return value specifies that A appears before B in the sorted sequence. o A return value of 0 specifies that A and B have the same sort order. o A positive return value specifies that A appears after B in the sorted sequence. • sortOptions - One or more numbers or defined constants, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. This argument is optional. The following values are acceptable for sortOptions: o 1 or Array.CASEINSENSITIVE o 2 or Array.DESCENDING o 4 or Array.UNIQUESORT o 8 or Array.RETURNINDEXEDARRAY o 16 or Array.NUMERIC For more information, see the Array.sortOn() method.
  • 24. Returns Array — The return value depends on whether you pass any arguments, as described in the following list: • If you specify a value of 4 or Array.UNIQUESORT for the sortOptions argument of the ...args parameter and two or more elements being sorted have identical sort fields, Flash returns a value of 0 and does not modify the array. • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for the sortOptions argument of the ...args parameter, Flash returns a sorted numeric array of the indices that reflects the results of the sort and does not modify the array. • Otherwise, Flash returns nothing and modifies the array to reflect the sort order.See also| (bitwise OR)Array.sortOn()Example ( How to use this example )The following code creates the Array object vegetables with elements [spinach, green pepper,cilantro, onion, avocado]. The array is then sorted by the sort() method, which is called with noparameters. The result is vegetables sorted in alphabetical order ([avocado, cilantro, greenpepper, onion, spinach]).var vegetables:Array = new Array("spinach", "green pepper", "cilantro", "onion", "avocado");trace(vegetables); // spinach,green pepper,cilantro,onion,avocadovegetables.sort();trace(vegetables); // avocado,cilantro,green pepper,onion,spinachThe following code creates the Array object vegetables with elements [spinach, green pepper,Cilantro, Onion, and Avocado]. The array is then sorted by the sort() method, which is called withno parameters the first time; the result is [Avocado,Cilantro,Onion,green pepper,spinach].Then sort() is called on vegetables again with the CASEINSENSITIVE constant as a parameter. Theresult isvegetables sorted in alphabetical order ([Avocado, Cilantro, green pepper, Onion,spinach]).var vegetables:Array = new Array("spinach", "green pepper", "Cilantro", "Onion",
  • 25. "Avocado");vegetables.sort();trace(vegetables); // Avocado,Cilantro,Onion,green pepper,spinachvegetables.sort(Array.CASEINSENSITIVE);trace(vegetables); // Avocado,Cilantro,green pepper,Onion,spinachThe following code creates the empty Array object vegetables, which is then populated through fivecalls to push(). Each time push() is called, a new Vegetable object is created by a call tothe Vegetable()constructor, which accepts a String (name) and Number (price) object.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 tosort 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.44vegetables.sort();trace(vegetables);// asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44//The following code defines the Vegetable classclass 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;
  • 26. }}The following example is exactly the same as the previous one, except that the sort() method is usedwith a custom sort function (sortOnPrice), which sorts according to price instead of alphabetically. Notethat 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.44vegetables.sort(sortOnPrice);trace(vegetables);// celery:1.29, squash:1.44, lettuce:1.49, spinach:1.89, asparagus:3.99function 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 { //aPrice == bPrice return 0; }}// The following code defines the Vegetable class and should be in a separate package.class Vegetable { private var name:String; private var price:Number;
  • 27. 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; }}The following code creates the Array object numbers with elements [3,5,100,34,10]. A callto sort() without any parameters sorts alphabetically, producing the undesiredresult [10,100,3,34,5]. To properly sort numeric values, you must pass the constant NUMERIC tothe sort() method, which sorts numbers as follows: [3,5,10,34,100].Note: The default behavior of the sort() function is to handle each entity as a string.The Array.NUMERIC argument does not actually convert other data types to the Number data type; itsimply allows the sort algorithm to recognize numbers.var numbers:Array = new Array(3,5,100,34,10);trace(numbers); // 3,5,100,34,10numbers.sort();trace(numbers); // 10,100,3,34,5numbers.sort(Array.NUMERIC);trace(numbers); // 3,5,10,34,100 sortO ( n ) methodAS3 function sortOn(fieldName:Object, options:Object = null):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Sorts the elements in an array according to one or more fields in the array. The array should have thefollowing characteristics:
  • 28. • The array is an indexed array, not an associative array. • Each element of the array holds an object with one or more properties. • All of the objects have at least one property in common, the values of which can be used to sort the array. Such a property is called a field.If you pass multiple fieldName parameters, the first field represents the primary sort field, the secondrepresents the next sort field, and so on. Flash sorts according to Unicode values. (ASCII is a subset ofUnicode.) If either of the elements being compared does not contain the field that is specified inthe fieldName parameter, the field is assumed to be set to undefined, and the elements are placedconsecutively in the sorted array in no particular order.By default, Array.sortOn() works in the following way: • Sorting is case-sensitive (Z precedes a). • Sorting is ascending (a precedes b). • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order. • Numeric fields are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".Flash Player 7 added the options parameter, which you can use to override the default sort behavior. Tosort a simple array (for example, an array with only one field), or to specify a sort order thatthe options parameter doesnt 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 morethan one field. In Flash Player 8 and later, the options parameter accepts an array of sort options suchthat each sort option corresponds to a sort field in the fieldName parameter. The following examplesorts 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 optionscan be used only as the first element in the array; otherwise, they are ignored.ParametersfieldName:Object — A string that identifies a field to be used as the sort value, or an array in which the firstelement 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 bythe bitwise OR (|) operator, that change the sorting behavior. The following values are acceptable fortheoptions parameter:
  • 29. • Array.CASEINSENSITIVE or 1 • Array.DESCENDING or 2 • Array.UNIQUESORT or 4 • Array.RETURNINDEXEDARRAY or 8 • Array.NUMERIC or 16Returns Array — The return value depends on whether you pass any parameters: • If you specify a value of 4 or Array.UNIQUESORT for the options parameter, and two or more elements being sorted have identical sort fields, a value of 0 is returned and the array is not modified. • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for the options parameter, an array is returned that reflects the results of the sort and the array is not modified. • Otherwise, nothing is returned and the array is modified to reflect the sort order.See also| (bitwise OR)Array.sort()Example ( How to use this example )The following code creates an empty Array object vegetables and the array is then populated using fivecalls to push(). Each time push() is called, a new Vegetable object is created by callingthe Vegetable()constructor, which accepts a String (name) and Number (price) object.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 usedwith the name parameter to produce the following array: [asparagus:3.99, celery:1.29,lettuce:1.49, spinach:1.89, squash:1.44]. ThesortOn() method is then called again with theprice parameter, and the NUMERIC and DESCENDING constants to produce an array sorted by numbersin 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.44vegetables.sortOn("name");trace(vegetables);
  • 30. // asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44vegetables.sortOn("price", Array.NUMERIC | Array.DESCENDING);trace(vegetables);// asparagus:3.99, spinach:1.89, lettuce:1.49, squash:1.44, celery:1.29class 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; }}The following code creates an empty Array object records and the array is then populated using threecalls to push(). Each time push() is called, the strings name and city and a zip number are addedto records. Three for loops are used to print the array elements. The first for loop prints the elementsin the order in which they were added. The second for loop is run after records has been sorted byname and then city using the sortOn() method. The third for loop produces different outputbecause records is re-sorted by city then by 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
  • 31. 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, omahatrace("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, omahaThe following code creates an empty Array object users and the array is then populated using four callsto push(). Each time push() is called, a User object is created with the User() constructor anda name string and age uint are added to users. The resulting array setis [Bob:3,barb:35,abcd:3,catchy:4].The array is then sorted in the following ways: 1. By name only, producing the array [Bob:3,abcd:3,barb:35,catchy:4] 2. By name and using the CASEINSENSITIVE constant, producing the array [abcd:3,barb:35,Bob:3,catchy:4] 3. By name and using the CASEINSENSITIVE and DESCENDING constants, producing the array [catchy:4,Bob:3,barb:35,abcd:3] 4. By age only, producing the array [abcd:3,Bob:3,barb:35,catchy:4] 5. By age and using the NUMERIC constant, producing the array [Bob:3,abcd:3,catchy:4,barb:35] 6. By age and using the DESCENDING and NUMERIC constants, producing the array [barb:35,catchy:4,Bob:3,abcd:3]An array called indices is then created and assigned the results of a sort by age and usingthe NUMERIC and RETURNINDEXEDARRAY constants, resulting in thearray [Bob:3,abcd:3,catchy:4,barb:35], which is then printed out using a for loop.
  • 32. 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:4users.sortOn("name");trace(users); // Bob:3,abcd:3,barb:35,catchy:4users.sortOn("name", Array.CASEINSENSITIVE);trace(users); // abcd:3,barb:35,Bob:3,catchy:4users.sortOn("name", Array.CASEINSENSITIVE | Array.DESCENDING);trace(users); // catchy:4,Bob:3,barb:35,abcd:3users.sortOn("age");trace(users); // abcd:3,Bob:3,barb:35,catchy:4users.sortOn("age", Array.NUMERIC);trace(users); // Bob:3,abcd:3,catchy:4,barb:35users.sortOn("age", Array.DESCENDING | Array.NUMERIC);trace(users); // barb:35,catchy:4,Bob:3,abcd:3
  • 33. 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 ( splice ) methodAS3 function splice(startIndex:int, deleteCount:uint, ... values):ArrayLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Adds elements to and removes elements from an array. This method modifies the array without making acopy.Note: To override this method in a subclass of Array, use ...args for the parameters, as this exampleshows: public override function splice(...args) { // your statements here }ParametersstartIndex:int — An integer that specifies the index of the element in the array where the insertion ordeletion begins. You can use a negative integer to specify a position relative to the end of the array (for example, -1is the last element of the array).deleteCount:uint — An integer that specifies the number of elements to be deleted. This number includes theelement specified in the startIndex parameter. If you do not specify a value for the deleteCountparameter, themethod deletes all of the values from the startIndex element to the last element in the array. If the value is 0, noelements are deleted.... values — An optional list of one or more comma-separated values to insert into the array at the positionspecified in the startIndex parameter. If an inserted value is of type Array, the array is kept intact and inserted asa single element. For example, if you splice an existing array of length three with another array of length three, theresulting array will have only four elements. One of the elements, however, will be an array of length three.Returns
  • 34. Array — An array containing the elements that were removed from the original array.Example ( How to use this example )The following code creates the Array object vegetables with the elements [spinach, green pepper,cilantro, onion, avocado]. The splice() method is then called with the parameters 2 and 2, whichassigns cilantro and onion to the spliced array. The vegetables array thencontains [spinach,green pepper,avocado]. The splice() method is called a second time using theparameters 1, 0, and thespliced array to assign [cilantro,onion] as the second elementin vegetables.var vegetables:Array = new Array("spinach", "green pepper", "cilantro", "onion", "avocado");var spliced:Array = vegetables.splice(2, 2);trace(vegetables); // spinach,green pepper,avocadotrace(spliced); // cilantro,onionvegetables.splice(1, 0, spliced);trace(vegetables); // spinach,cilantro,onion,green pepper,avocadoNotice that cilantro and onion trace out as if vegetables has 5 elements, even though it actually hasfour (and the second element is another array containing two elements). Toadd cilantro and onionindividually, you would use: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, "cilantro", "onion"); trace(vegetables); // spinach,cilantro,onion,green pepper,avocado
  • 35. ( toLocaleString )methodpublic function toLocaleString():StringLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Returns a string that represents the elements in the specified array. Every element in the array, startingwith index 0 and ending with the highest index, is converted to a concatenated string and separated bycommas. In the ActionScript 3.0 implementation, this method returns the same value asthe Array.toString() method.Returns String — A string of array elements.See alsoArray.toString() toStrin ( g ) methodpublic function toString():StringLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Returns a string that represents the elements in the specified array. Every element in the array, startingwith index 0 and ending with the highest index, is converted to a concatenated string and separated bycommas. To specify a custom separator, use the Array.join() method.Returns String — A string of array elements.See alsoString.split()Array.join()Example ( How to use this example )The following code creates an Array, converts the values to strings, and stores them inthe vegnums variable of the String data type.
  • 36. var vegetables:Array = new Array();vegetables.push(1);vegetables.push(2);vegetables.push(3);vegetables.push(4);vegetables.push(5);var vegnums:String = vegetables.toString();trace(vegnums+",6");// 1,2,3,4,5,6 ( unshift )methodAS3 function unshift(... args):uintLanguage ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Adds one or more elements to the beginning of an array and returns the new length of the array. Theother elements in the array are moved from their original position, i, to i+1.Parameters... args — One or more numbers, elements, or variables to be inserted at the beginning of thearray.Returns uint — An integer representing the new length of the array.See alsoArray.pop()Array.push()Array.shift()Example ( How to use this example )The following code creates the empty Array object names. The strings Bill and Jeff are added bythe push() method, and then the strings Alfred and Kyle are added to the beginning of names by twocalls to theunshift() method.var names:Array = new Array();names.push("Bill");names.push("Jeff");trace(names); // Bill,Jeff
  • 37. names.unshift("Alfred");names.unshift("Kyle");trace(names); // Kyle,Alfred,Bill,JeffConstant Detail CASEINSENSITIVE Constantpublic static const CASEINSENSITIVE:uint = 1Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Specifies case-insensitive sorting for the Array class sorting methods. You can use this constant forthe options parameter in the sort() or sortOn() method.The value of this constant is 1.See alsoArray.sort()Array.sortOn() DESCENDING Constantpublic static const DESCENDING:uint = 2Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Specifies descending sorting for the Array class sorting methods. You can use this constant forthe options parameter in the sort() or sortOn() method.The value of this constant is 2.See alsoArray.sort()Array.sortOn() NUMERIC Constantpublic static const NUMERIC:uint = 16Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0
  • 38. Versions:Specifies numeric (instead of character-string) sorting for the Array class sorting methods. Including thisconstant in the options parameter causes the sort() and sortOn() methods to sort numbers asnumeric values, not as strings of numeric characters. Without the NUMERIC constant, sorting treats eacharray 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 inthe options parameter, the sorted array is [2005, 35, 7], but if the NUMERIC constant is included, thesorted array is [7, 35, 2005].This constant applies only to numbers in the array; it does not apply to strings that contain numeric datasuch as ["23", "5"].The value of this constant is 16.See alsoArray.sort()Array.sortOn() RETURNINDEXEDARRAY Constantpublic static const RETURNINDEXEDARRAY:uint = 8Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Specifies that a sort returns an array that consists of array indices. You can use this constant forthe options parameter in the sort() or sortOn() method, so you have access to multiple views of thearray elements while the original array is unmodified.The value of this constant is 8.See alsoArray.sort()Array.sortOn() UNIQUESORT Constantpublic static const UNIQUESORT:uint = 4Language ActionScript 3.0Version:Runtime Flash Player 9, AIR 1.0Versions:Specifies the unique sorting requirement for the Array class sorting methods. You can use this constantfor the options parameter in the sort() or sortOn() method. The unique sorting option terminates thesort if any two elements or fields being sorted have identical values.
  • 39. The value of this constant is 4.See alsoArray.sort()Array.sortOn()Examples ( How to use this example )ArrayExample.asThe following example creates a new Array object 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 } }} © 2009 Adobe Systems Incorporated. All rights reserved. Sat Oct 3 2009, 04:15 AM -07:00