JavaScript Kit > JavaScript Reference > Here
Array Object
There are three ways of defining an array:
var myfriends=new Array() //1) regular array. Pass an optional integer argument to control array's size.
myfriends[0]="John"
myfriends[1]="Bob"
myfriends[2]="Sue"
var myfriends=new Array("John", "Bob", "Sue") //2) condensed array
var myfriends=["John", "Bob", "Sue"] //3) literal array
Related Tutorials
- Understanding basic arrays and loops
- Understanding dense arrays
- Defining arrays using literal notation (covers multi-dimensional arrays)
- Sorting an array using the sort() method
Properties
Properties | Description |
---|---|
length | A read/write property indicating the current number of elements within the array. You may set this property to dynamically expand an array's length. |
prototype | Use this property to attach additional properties and/or methods that get reflected in all instances of the array. |
Methods
Note: "[]" surrounding a parameter below means the parameter is optional.
Methods | Description | ||||||
---|---|---|---|---|---|---|---|
Array.isArray(testobject)
This is a JavaScript1.8.5 feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera 10.5+.
|
Method that tests whether an object is an Array or not. Pass into Array.isArray() the object to test, for example:
Array.isArray("test string") //returns false, string Until all major supports Array.isArray natively, you can define your own custom isArray() method for those browsers that don't: Cross browser isArray() function: Array.isArray = function(test){ The custom function that targets browsers that don't support |
||||||
concat(value1, ...) |
Concatenates either plain values or another array with the existing array, and returns the new array. Does NOT alter the original array. Example.
Note: If the values to concat are strings or numbers, their actual values are added to the returned array. If the values to concat are object references, the same object reference will be added, and not the object itself. This means that both the old and new array will now contain references to those object(s), with changes to the referenced object affecting both arrays. |
||||||
every(testfunction[thisobj])
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Traverses an array and only returns true if all elements within it satisfies the condition set forth by testfunction() . Use it for example to test if all values within an array is greater than 0. Compliments the array method some()
testfunction(elementValue, elementIndex, targetArray){ The three arguments are passed implicitly into the function, containing the current element value, index, plus the array being manipulated. Example: Here's an example that quickly scans an array to make sure all of its elements' value is greater than 0. var numbersarray=[2, 4, 5, -1, 34] The |
||||||
filter(testfunction[thisobj])
This is a JavaScript1.6 feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Returns a new array containing all elements of the existing array that pass the condition set forth by testfunction() . Original array is not changed. Use it to filter down an array based on the desired condition.
var numbersarray=[-3, 5, 34, 19] |
||||||
forEach(functionref)
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Iterates through the array and executes function testfunction() on each of its element. The processing function cannot return a value, so the result must be handled immediately. Use it for example to print out the value of all of the array elements.
var numbersarray=[-3, 5, 34, 19] |
||||||
indexOf(targetElement, [startIndex])
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Returns the first index in which targetElment (value) is found within an array, or -1 if nothing is found. An optional [startIndex] lets you specify the position in which to begin the search (default is 0, or search entire array):
var fruits=["Apple", "Oranges", "Pork", "Chicken"] |
||||||
join([separator]) |
Converts each element within the array to a string, and joins them into one large string. Pass in an optional separator as argument to be used to separate each array element. If none is passed, the default comma (') is used:
var fruits=["Apple", "Oranges"] |
||||||
lastIndexOf(targetElement, [startIndex]
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Returns the first index in which targetElment (value) is found within an array starting from the last element and backwards, or -1 if nothing is found. An optional [startIndex] lets you specify the position in which to begin the search (default is array.length-1, or search entire array). | ||||||
map(testfunction[thisobj])
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Returns a new array based on the return value of testfunction() on each of the array elements. Original array is not changed. Use it to transform the values of all elements within an array using some logic and derive the results as a new array.
var numbersarray=[-3, 5, 34, 19] |
||||||
pop() | Deletes the last element within array and returns the deleted element. Original array is modified. | ||||||
push(value1, ...) | Adds the argument values to the end of the array, and modifies the original array with the new additions. Returns the new length of the array. | ||||||
reduce(callbackfunction, [initialvalue])
JavaScript1.6 feature, supported in IE9+ (strict mode), FF3+, Chrome, Safari, and Opera 10.5+ |
reduce() lets you invoke a callback function sequentially on the array's elements until the last element (starting from the first if the intialvalue parameter of the callback function is defined), returning the cumulative result of all of the operations combined as a single value. It's a handy feature for performing computations that involve all of the array elements. The original array is NOT modified. For example, to obtain the sum of all the elements inside an array, you could use reduce as follows:
var total = [1,2,3,4].reduce(function(prevresult, cur){ // total returns 10 The call back function is called 3 times in the above case, using the first array element (1) as the initial value but executing the function calls starting from the 2nd element and until the end. Each time the return value of the callback function is fed back to the
Array.reduce( function(callbackfunction, [initialvalue]){
The following var x = [{total:5}, {total:7}, {total:3}] Lets see an example of y = [1, 2, 3, 4, 5, 6, 7, 8] Notice the value of the |
||||||
reduceRight(callbackfunction, [initialvalue])
JavaScript1.6 feature, supported in IE9+ (strict mode), FF3+, Chrome, Safari, and Opera 10.5+ |
Calls the desired function on each of the elements within an array (right to left), returning the cumulative result of all the function calls as a single value. Identical to reduce above except for the direction of the operation (right to left versus left to right). |
||||||
reverse() | Reverses the order of all elements within the array. Original array is modified. | ||||||
shift() |
Deletes and returns the first element within the array. Original array is modified to account for the missing element (so 2nd element now becomes the first etc).
See also |
||||||
slice(start, [end]) | Returns a "slice" of the original array based on the start and end arguments. Original array is not changed. The slice includes the new array referenced by the start index and up to but NOT including the end index itself. If "end" is not specified, the end of the array is assumed. | ||||||
splice(startIndex, [how_many], [value1, ...]) |
Deletes how_many array elements starting from startIndex, and optionally replaces them with value1, value2 etc. Original array is modified. You can use splice() to delete an element from an array. Example(s).
This method returns the elements deleted from array. |
||||||
some(testfunction[thisobj])
This is a JavaScript1.6 feature, feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera. |
Traverses an array and returns true if any one of its elements satisfies the condition set forth by testfunction() . Use it for example to test if at least one element value within the array is above 0. Compliments the array method every() Example(s).
var numbersarray=[-3, -34, 1, 32, -100] The |
||||||
sort([SortFunction]) |
By default sorts an array alphabetically and ascending. By passing in an optional SortFunction , you can sort numerically and by other criteria as well.
If
Take a look at the following 3 distinct examples: //Sort Alphabetically and ascending: //Sort numerically and ascending: //Randomize the order of the array: To sort numerically, you need to compare the relationship between " To sort randomly, you need to return a random number that can randomly be You can also sort arrays that contain more than just primitive values, but objects with properties. See the tutorial: Sorting an Array of Objects. |
||||||
toSource() | Returns an array literal representing the specified array. | ||||||
toString() | Returns a string representing the array and its elements. | ||||||
unshift(value1, ...) |
Adds the argument values to the beginning of the array, pushing existing arrays back. Returns the new length of the array. Original array is modified:
var fruits=["Apple", "Oranges"] |
||||||
valueOf() | Returns the primitive value of the array. |
Examples
concat(value1,...)
var fruits=["Apple", "Oranges"]
var meat=["Pork", "Chicken"]
var dinner=fruits.concat(meat) //creates ["Apple", "Oranges", "Pork", "Chicken"]. fruits and meat arrays not changed.
var snack=fruits.concat("Grapes", ["Cookies", "Milk"]) //creates ["Apple", "Oranges", "Grapes", "Cookies", "Milk"] fruits array not changed.
splice(startIndex, [how_many], [value1, ...])
Splice() is one of those array functions that can use some explanation. Lets look at its parameters in detail:
1) startIndex- the array element to begin the insertion or deletion of the array.
2) how_many- the number of elements, beginning with the element specified in startIndex, to delete from the array. Optional. Not specifying this parameter causes all elements starting from startIndex to be deleted.
3) value1, value2 etc- Optional values to be inserted into the array, starting at startIndex.
var myarray=[13, 36, 25, 52, 83]
myarray.splice(2, 2) //myarray is now [13, 36 , 83]. The 3rd and 4th element is removed.
var myarray=[13, 36, 25, 52, 83] //reset array for 2nd example
myarray.splice(2, 3, 42, 15) //myarray is now [13, 36 , 42, 15]. The 3rd, 4th and 5th element is removed, replaced with 42 and 15.
- JavaScript Operators
- JavaScript Statements
- Global functions
- JavaScript Events
- Escape Sequences
- Reserved Words