Array NN 3 IE 4 ECMA 1  

  

An array is an ordered collection of one or more pieces of data. JavaScript array entries may be of any data type, and you can mix different data types in the same array. Each entry in an array has an index assigned to it. The default behavior is for the index to be a zero-based integer (the first entry has an index of zero). An index value may also be a string, but the string index acts like a property name of an array object, and does not influence the numeric indices (which is why string-indexed entries cannot be iterated via the array's length property, but can be iterated via a for-in loop). Separate sets of integer- and string-indexed items can coexist within the same array object.

 

Accessing an entry in an array requires the name of the array and the index in square brackets:

cars[0]
cars["Ford"]
 

You may also create an array of arrays to simulate multidimensional arrays. A reference to an item in a two-dimensional array uses syntax as follows:

myArray[x][y]
 

The number of entries in a JavaScript array (its length) can vary over time. Therefore, you do not have to initialize an empty array to a specific size (nor is there any particular advantage to doing so). To add a new entry to an array of indeterminant length, assign the value to the next higher array index value:

cars[cars.length] = "Bentley";
 

A shortcut array creation technique is available starting in IE 4 and Navigator 4, using square brackets to contain values in literal notation.

 
Properties
 
constructor length prototype
 
Methods
 
concat( ) join( ) pop( )
push( ) reverse( ) shift( )
slice( ) sort( ) splice( )
toLocaleString( ) toString( ) unshift( )
 
Creating an Array
 
var myArray = new Array( );
var myArray = new Array(sizeInteger);
var myArray = new Array(element0, element1, ..., elementN);
var myArray = [element0, element1, ..., elementN];
constructor NN 4 IE 4 ECMA 1  

Read/Write  

This is a reference to the function that created the instance of an Array objectthe native Array( ) constructor function in browsers.

 
Example
 
if (myVar.constructor == Array) {
    // process native string
}
 
Value

Function object reference.

length NN 3 IE 4 ECMA 1  

Read/Write  

Provides a count of the number of numerically-indexed entries stored in the array. If the constructor function used to create the array specified a preliminary length, the length property reflects that amount, even if data does not occupy every slot.

 
Example
 
for (var i = 0; i < myArray.length; i++) {
    ...
}
 
Value

Integer.

prototype NN 3 IE 4 ECMA 1  

Read/Write  

This is a property of the static Array object. Use the prototype property to assign new properties and methods to future instances of arrays created in the current document. For example, the following function creates a return-delimited list of elements in an array in reverse order:

function formatAsList( ) {
    var output = "";
    for (var i = this.length - 1; i>= 0; i--) {
        output += this[i] + "\n";
    }
    alert(output);
} 
 

To give an array that power, assign this function reference to a prototype property whose name you want to use as the method to invoke this function:

Array.prototype.showReverseList = formatAsList;
 

If a script creates an array at this point:

var stooges = new Array("Moe", "Larry", "Curly", "Shemp");

the new array has the showReverseList( ) method available to it. To invoke the method, the call is:

stooges.showReverseList( );
 

You can add properties the same way. These allow you to attach information about the array (its creation time, for example) without disturbing the ordered sequence of array data. When a new document loads into the window or frame, the static Array object starts fresh again.

 
Example
 
Array.prototype.created = "";
 
Value

Any data, including function references.

concat( ) NN 4 IE 4 ECMA 3  

concat(item1[, item2[, ...itemN]])

  

Returns an array that combines the current array object with one or more array objects (or other values) specified as the method parameter(s):

var combinedArray = myArray1.concat(myArray2, someValue);

Neither of the original arrays is altered in the process.

 
Parameters
 
item1...itemN

Any JavaScript value, including another array.

 
Returned Value

An Array object.

join( ) NN 3 IE 4 ECMA 1  

join(["delimiterString"])

  

Returns a string consisting of a list of items (as strings) contained by an array. The delimiter character(s) between items is set by the parameter to the method. Note that an array's items are only those items that are accessible via an integer index. Items referenced via string index values are treated as properties of the array object, and are thus independent of integer indexed values (the two sets can coexist in a single array without conflict). The join( ) method works only with the integer-indexed items.

 
Parameters
 
delimiterString

Any string of characters. Nonalphanumeric characters must use URL-encoded equivalents (%0D for carriage return). The default delimiter string is a comma character.

 
Returned Value

String.

pop( ) NN 4 IE 5.5(Win) ECMA 2  

  

Returns the value of the last item in an array and removes it from the array. The length of the array decreases by one.

 
Parameters

None.

 
Returned Value

Any JavaScript value.

push( ) NN 4 IE 5.5(Win) ECMA 2  

push(item1[, item2[, ...itemN]])

  

Appends one or more items to the end of an array. The length of the array increases by one.

 
Parameters
 
item1...itemN

Comma-delimited list of one or more JavaScript values, including object references.

 
Returned Value

The value pushed into the array.

reverse( ) NN 3 IE 4 ECMA 1  

  

Reverses the order of items in the array and returns a copy of the array in the new order. Not only does the reverse( ) method rearrange the values in the array, but it also returns a copy of the reversed array.

 
Parameters

None.

 
Returned Value

An Array object.

shift( ) NN 4 IE 5.5(Win) ECMA 2  

  

Returns the value of the first item in an array and removes it from the array. The length of the array decreases by one.

 
Parameters

None.

 
Returned Value

Any JavaScript value.

slice( ) NN 4 IE 4 ECMA 2  

slice(startIndex[, endIndex])

  

Returns an array that is a subset of contiguous items from the main array. Parameters determine where the selection begins and ends.

 
Parameters
 
startIndex

A zero-based integer of the first item of the subset from the current array.

endIndex

An optional zero-based integer of the last item of the subset from the current array. If omitted, the selection is made from the startIndex position to the end of the array.

 
Returned Value

An Array object.

sort( ) NN 3 IE 4 ECMA 1  

sort([compareFunction])

  

Sorts the values of the array either by the ASCII value of string versions of each array entry or according to a comparison function of your own design. The sort( ) method repeatedly invokes the comparison function, passing two values from the array. The comparison function should return an integer value, which is interpreted by the sort( ) function as follows.

 
Value Meaning
<0 The second passed value should sort later than the first value.
0 The sort order of the two values should not change.
>0 The first passed value should sort later than the second.
 

The following comparison function sorts values of an array in numerical (instead of ASCII) order:

function doCompare(a, b) {
    return a - b
}

To sort an array by this function, the statement is:

myArray.sort(doCompare)

By the time the sort( ) method has completed its job, it has sent all values to the doCompare( ) function two values at a time and sorted the values on whether the first value is larger than the second (in the manner of a bubble sort).

Not only does the sort( ) method rearrange the values in the array, but it also returns a copy of the sorted array.

 
Parameters
 
compareFunction

A reference to a function that receives two parameters and returns an integer result.

 
Returned Value

An Array object, sorted according to sorting criteria.

splice( ) NN 4 IE 5.5(Win) ECMA 2  

splice(startIndex, deleteCount[, item1[, item2[, ...itemN]]])

  

Removes one or more contiguous items from within an array and, optionally, inserts new items in their places. The length of the array adjusts itself accordingly.

 
Parameters
 
startIndex

A zero-based integer of the first item of the subset from the current array.

deleteCount

An integer denoting how many items from the startIndex position are to be removed from the array.

item1...itemN

Comma-delimited list of JavaScript values to be inserted into the array in place of removed items. The number of items does not have to equal deleteCount.

 
Returned Value

An Array object containing removed items.

toLocaleString( ) NN 6 IE 5.5(Win) ECMA 2  

  

Returns a comma-delimited string of values, theoretically in a format tailored to the language and customs of the browser's default language. Implementation details vary with browser and data type. IE 5.5 and later converts numbers of all kinds to strings with two digits to the right of the decimal, but triggers an error for object references. Netscape 6 leaves integers in their original format and displays object references as [object objectType]. The ECMA standard leaves such interpretations up to the browser maker.

 
Parameters

None.

 
Returned Value

Comma-delimited string.

toString( ) NN 3 IE 4 ECMA 1  

  

Returns a comma-delimited string of values, identical to using the Array.join( ) method with a comma parameter. All values are converted to some string equivalent, including objects ([object] in IE/Windows; [object objectType] in IE 5/Macintosh and Netscape 6).

 
Parameters

None.

 
Returned Value

Comma-delimited string.

unshift( ) NN 4 IE 5.5(Win) ECMA 2  

unshift(item1[, item2[, ...itemN]])

  

Inserts one or more items at the beginning of an array. The length of the array increases by the number of items added, and the method returns the new length of the array.

 
Parameters
 
item1...itemN

Comma-delimited list of one or more JavaScript values.

 
Returned Value

Integer.