Previous     Contents     Index     Next     
Core JavaScript Reference 1.5





Array

Lets you work with arrays.


Core object

Implemented in  

JavaScript 1.1, NES 2.0

JavaScript 1.3: added toSource method; changed length property; changed push method  

ECMA version  

ECMA-262  


Created by
The Array object constructor:

new Array(arrayLength)
new Array(element0, element1, ..., elementN)

An array literal:

[element0, element1, ..., elementN]

JavaScript 1.2 when you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag:

new Array(element0, element1, ..., elementN)

JavaScript 1.2 when you do not specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag:

new Array([arrayLength])
new Array([element0[, element1[, ..., elementN]]])

JavaScript 1.1:

new Array([arrayLength])
new Array([element0[, element1[, ..., elementN]]])


Parameters


arrayLength

 

The initial length of the array. You can access this value using the length property. If the value specified is not a number, an array of length 1 is created, with the first element having the specified value. The maximum length allowed for an array is 4,294,967,295.  

elementN

 

A list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length property is set to the number of arguments.  


Description
An array is an ordered set of values associated with a single variable name.

The following example creates an Array object with an array literal; the coffees array contains three elements and a length of three:

coffees = ["French Roast", "Columbian", "Kona"]

You can construct a dense array of two or more elements starting with index 0 if you define initial values for all elements. A dense array is one in which each element has a value. The following code creates a dense array with three elements:

myArray = new Array("Hello", myVar, 3.14159)

Indexing an array. You index an array by its ordinal number. For example, assume you define the following array:

myArray = new Array("Wind","Rain","Fire")

You then refer to the first element of the array as myArray[0] and the second element of the array as myArray[1].

Specifying a single parameter. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The following code creates an array of five elements:

billingMethod = new Array(5)

The behavior of the Array constructor depends on whether the single parameter is a number.

The following code creates an array of length 25, then assigns values to the first three elements:

musicTypes = new Array(25)
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"

Increasing the array length indirectly. An array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length 0, then assigns a value to element 99. This changes the length of the array to 100.

colors = new Array()
colors[99] = "midnightblue"

Creating an array using the result of a match. The result of a match between a regular expression and a string can create an array. This array has properties and elements that provide information about the match. An array is the return value of RegExp.exec, String.match, and String.replace. To help explain these properties and elements, look at the following example and then refer to the table below:

<SCRIPT LANGUAGE="JavaScript1.2">
//Match one d followed by one or more b's followed by one d
//Remember matched b's and the following d
//Ignore case

myRe=/d(b+)(d)/i;
myArray = myRe.exec("cdbBdbsbz");

</SCRIPT>

The properties and elements returned from this match are as follows:




Property/Element

Description

Example

input

 

A read-only property that reflects the original string against which the regular expression was matched.  

cdbBdbsbz  

index

 

A read-only property that is the zero-based index of the match in the string.  

1  

[0]

 

A read-only element that specifies the last matched characters.  

dbBd  

[1], ...[n]

 

Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.  

[1]=bB 
[2]=d
 


Backward Compatibility

JavaScript 1.2. When you specify a single parameter with the Array constructor, the behavior depends on whether you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag:

JavaScript 1.1 and earlier. When you specify a single parameter with the Array constructor, you specify the initial length of the array. The following code creates an array of five elements:

billingMethod = new Array(5)

JavaScript 1.0. You must index an array by its ordinal number; for example myArray[0].


Property Summary      



Property

Description

constructor

 

Specifies the function that creates an object's prototype.  

index

 

For an array created by a regular expression match, the zero-based index of the match in the string.  

input

 

For an array created by a regular expression match, reflects the original string against which the regular expression was matched.  

length

 

Reflects the number of elements in an array.  

prototype

 

Allows the addition of properties to all objects.  


Method Summary



Method

Description

concat

 

Joins two arrays and returns a new array.  

join

 

Joins all elements of an array into a string.  

pop

 

Removes the last element from an array and returns that element.  

push

 

Adds one or more elements to the end of an array and returns the new length of the array.  

reverse

 

Transposes the elements of an array: the first array element becomes the last and the last becomes the first.  

shift

 

Removes the first element from an array and returns that element.  

slice

 

Extracts a section of an array and returns a new array.  

splice

 

Adds and/or removes elements from an array.  

sort

 

Sorts the elements of an array.  

toSource

 

Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.toSource method.  

toString

 

Returns a string representing the array and its elements. Overrides the Object.toString method.  

unshift

 

Adds one or more elements to the front of an array and returns the new length of the array.  

valueOf

 

Returns the primitive value of the array. Overrides the Object.valueOf method.  

In addition, this object inherits the watch and unwatch methods from Object.


Examples
Example 1. The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

msgArray = new Array()
msgArray[0] = "Hello"
msgArray[99] = "world"
// The following statement is true,
// because defined msgArray[99] element.
if (msgArray.length == 100)
   myVar="The length is 100."

Example 2: Two-dimensional array. The following code creates a two-dimensional array and assigns the results to myVar.

myVar="Multidimensional array test; "
a = new Array(4)
for (i=0; i < 4; i++) {
   a[i] = new Array(4)
   for (j=0; j < 4; j++) {
      a[i][j] = "["+i+","+j+"]"
   }
}
for (i=0; i < 4; i++) {
   str = "Row "+i+":"
   for (j=0; j < 4; j++) {
      str += a[i][j]
   }
   myVar += str +"; "
}

This example assigns the following string to myVar (line breaks are used here for readability):

Multidimensional array test;
Row 0:[0,0][0,1][0,2][0,3];
Row 1:[1,0][1,1][1,2][1,3];
Row 2:[2,0][2,1][2,2][2,3];
Row 3:[3,0][3,1][3,2][3,3];


concat

Joins two arrays and returns a new array.



Method of  

Array  

Implemented in  

JavaScript 1.2, NES 3.0  

ECMA version  

ECMA-262  


Syntax
concat(arrayName2, arrayName3, ..., arrayNameN)


Parameters



arrayName2...
arrayNameN

 

Arrays to concatenate to this array.  


Description
concat does not alter the original arrays, but returns a "one level deep" copy that contains copies of the same elements combined from the original arrays. Elements of the original arrays are copied into the new array as follows:

If a new element is added to either array, the other array is not affected.

The following code concatenates two arrays:

alpha=new Array("a","b","c")
numeric=new Array(1,2,3)
alphaNumeric=alpha.concat(numeric) // creates array ["a","b","c",1,2,3]

The following code concatenates three arrays:

num1=[1,2,3]
num2=[4,5,6]
num3=[7,8,9]
nums=num1.concat(num2,num3) // creates array [1,2,3,4,5,6,7,8,9]


constructor

Specifies the function that creates an object's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name.



Property of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0  

ECMA version  

ECMA-262  


Description
See Object.constructor.


index

For an array created by a regular expression match, the zero-based index of the match in the string.



Property of  

Array  

Static

Implemented in  

JavaScript 1.2, NES 3.0  


input

For an array created by a regular expression match, reflects the original string against which the regular expression was matched.



Property of  

Array  

Static

Implemented in  

JavaScript 1.2, NES 3.0  


join

Joins all elements of an array into a string.



Method of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0  

ECMA version  

ECMA-262  


Syntax
join(separator)


Parameters



separator

 

Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.  


Description
The string conversions of all array elements are joined into one string.


Examples
The following example creates an array, a, with three elements, then joins the array three times: using the default separator, then a comma and a space, and then a plus.

a = new Array("Wind","Rain","Fire")
myVar1=a.join()      // assigns "Wind,Rain,Fire" to myVar1
myVar2=a.join(", ")  // assigns "Wind, Rain, Fire" to myVar1
myVar3=a.join(" + ") // assigns "Wind + Rain + Fire" to myVar1


See also
Array.reverse


length

An unsigned, 32-bit integer that specifies the number of elements in an array.



Property of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0

JavaScript 1.3: length is an unsigned, 32-bit integer with a value less than 232.  

ECMA version  

ECMA-262  


Description
The value of the length property is an integer with a positive sign and a value less than 2 to the 32 power (232).

You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements.


Examples
In the following example, the getChoice function uses the length property to iterate over every element in the musicType array. musicType is a select element on the musicForm form.

function getChoice() {
   for (var i = 0; i < document.musicForm.musicType.length; i++) {
      if (document.musicForm.musicType.options[i].selected == true) {
         return document.musicForm.musicType.options[i].text
      }
   }
}

The following example shortens the array statesUS to a length of 50 if the current length is greater than 50.

if (statesUS.length > 50) {
   statesUS.length=50
}


pop

Removes the last element from an array and returns that element. This method changes the length of the array.



Method of  

Array  

Implemented in  

JavaScript 1.2, NES 3.0  

ECMA version  

ECMA-262 Edition 3  


Syntax
pop()


Parameters
None.


Example
The following code creates the myFish array containing four elements, then removes its last element.

myFish = ["angel", "clown", "mandarin", "surgeon"];
popped = myFish.pop();


See also
push, shift, unshift


prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.



Property of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0  

ECMA version  

ECMA-262  


push

Adds one or more elements to the end of an array and returns the new length of the array. This method changes the length of the array.



Method of  

Array  

Implemented in  

JavaScript 1.2, NES 3.0

JavaScript 1.3: push returns the new length of the array rather than the last element added to the array.  

ECMA version  

ECMA-262 Edition 3  


Syntax
push(element1, ..., elementN)


Parameters



element1, ...,
elementN

 

The elements to add to the end of the array.  


Description
The behavior of the push method is analogous to the push function in Perl 4. Note that this behavior is different in Perl 5.


Backward Compatibility

JavaScript 1.2. The push method returns the last element added to an array.


Example
The following code creates the myFish array containing two elements, then adds two elements to it. After the code executes, pushed contains 4. (In JavaScript 1.2, pushed contains "lion" after the code executes.)

myFish = ["angel", "clown"];
pushed = myFish.push("drum", "lion");


See also
pop, shift, unshift


reverse

Transposes the elements of an array: the first array element becomes the last and the last becomes the first.



Method of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0  

ECMA version  

ECMA-262  


Syntax
reverse()


Parameters
None


Description
The reverse method transposes the elements of the calling array object.


Examples
The following example creates an array myArray, containing three elements, then reverses the array.

myArray = new Array("one", "two", "three")
myArray.reverse()

This code changes myArray so that:


See also
Array.join, Array.sort


shift

Removes the first element from an array and returns that element. This method changes the length of the array.



Method of  

Array  

Implemented in  

JavaScript 1.2, NES 3.0  

ECMA version  

ECMA-262 Edition 3  


Syntax
shift()


Parameters
None.


Example
The following code displays the myFish array before and after removing its first element. It also displays the removed element:

myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish before: " + myFish);
shifted = myFish.shift();
document.writeln("myFish after: " + myFish);
document.writeln("Removed this element: " + shifted);

This example displays the following:

myFish before: ["angel", "clown", "mandarin", "surgeon"]
myFish after: ["clown", "mandarin", "surgeon"]
Removed this element: angel


See also
pop, push, unshift


slice

Extracts a section of an array and returns a new array.



Method of  

Array  

Implemented in  

JavaScript 1.2, NES 3.0  

ECMA version  

ECMA-262 Edition 3  


Syntax
slice(begin[,end])


Parameters



begin

 

Zero-based index at which to begin extraction.  

end

 

Zero-based index at which to end extraction:

  • slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

  • As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second to last element in the sequence.

  • If end is omitted, slice extracts to the end of the sequence.
 


Description
slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

If a new element is added to either array, the other array is not affected.


Example
In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

<SCRIPT LANGUAGE="JavaScript1.2">

//Using slice, create newCar from myCar.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}
myCar = [myHonda, 2, "cherry condition", "purchased 1997"]
newCar = myCar.slice(0,2)

//Write the values of myCar, newCar, and the color of myHonda
// referenced from both arrays.
document.write("myCar = " + myCar + "<BR>")
document.write("newCar = " + newCar + "<BR>")
document.write("myCar[0].color = " + myCar[0].color + "<BR>")
document.write("newCar[0].color = " + newCar[0].color + "<BR><BR>")

//Change the color of myHonda.
myHonda.color = "purple"
document.write("The new color of my Honda is " + myHonda.color + "<BR><BR>")

//Write the color of myHonda referenced from both arrays.
document.write("myCar[0].color = " + myCar[0].color + "<BR>")
document.write("newCar[0].color = " + newCar[0].color + "<BR>")

</SCRIPT>

This script writes:

myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2,
   "cherry condition", "purchased 1997"]
newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple


sort

Sorts the elements of an array.



Method of  

Array  

Implemented in  

JavaScript 1.1, NES 2.0

JavaScript 1.2: modified behavior.  

ECMA version  

ECMA-262  


Syntax
sort(compareFunction)