[Contents] [Previous] [Next] [Index]

Array

Represents an array of elements.

Core object

Implemented in

Navigator 3.0, LiveWire 1.0

Created by

The Array object constructor:

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

Parameters

arrayLength
(Optional) The initial length of the array. You can access this value using the length property.

elementN
(Optional) 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

In Navigator 3.0, you can specify an initial length when you create the array. The following code creates an array of five elements:

billingMethod = new Array(5)
When you create an array, all of its elements are initially null. The following code creates an array of 25 elements, then assigns values to the first three elements:

musicTypes = new Array(25)
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
However, in Navigator 4.0, if you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag, using new Array(1) creates a new array with a[0]=1.

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"
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)
In Navigator 2.0, you must index an array by its ordinal number, for example document.forms[0]. In Navigator 3.0 and later, you can index an array by either its ordinal number or by its name (if defined). For example, assume you define the following array:

myArray = new Array("Wind","Rain","Fire")
You can then refer to the first element of the array as myArray[0] or myArray["Wind"].

In Navigator 4.0, 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

Property Summary      

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 an Array object.

Method Summary

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 that last element added.

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.

toString
Returns a string representing the specified object.

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

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)
   document.write("The length is 100.")
See also examples for onError.

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

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]
   }
   document.write(str,"<p>")
}
This example displays the following results:

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]

See also

Image

Properties

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

Navigator 4.0, Netscape Server 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

Navigator 4.0, Netscape Server 3.0

length

An integer that specifies the number of elements in an array. You can set the length property to truncate an array at any time. You cannot extend an array; for example, if you set length to 3 when it is currently 2, the array will still contain only 2 elements.

Property of

Array

Implemented in

Navigator 3.0, LiveWire 1.0

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
   alert("The U.S. has only 50 states. New length is " + statesUS.length)
}

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

Navigator 3.0, LiveWire 1.0

Methods

concat

Joins two arrays and returns a new array.

Method of

Array

Implemented in

Navigator 4.0, Netscape Server 3.0

Syntax

concat(arrayName2)

Parameters

arrayName2
Name of the array 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.

join

Joins all elements of an array into a string.

Method of

Array

Implemented in

Navigator 3.0, LiveWire 1.0

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 conversion 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")
document.write(a.join() +"<BR>")
document.write(a.join(", ") +"<BR>")
document.write(a.join(" + ") +"<BR>")
This code produces the following output:

Wind,Rain,Fire
Wind, Rain, Fire
Wind + Rain + Fire

See also

Array.reverse

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

Navigator 4.0, Netscape Server 3.0

Syntax

pop()

Parameters

None.

Example

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

myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish before: " + myFish);
popped = myFish.pop();
document.writeln("myFish after: " + myFish);
document.writeln("popped this element: " + popped);
This example displays the following:

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

See also

push, shift, unshift

push

Adds one or more elements to the end of an array and returns that last element added. This method changes the length of the array.

Method of

Array

Implemented in

Navigator 4.0, Netscape Server 3.0

Syntax

push(elt1, ..., eltN)

Parameters

elt1, ..., eltN
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.

Example

The following code displays the myFish array before and after adding elements to its end. It also displays the last element added:

myFish = ["angel", "clown"];
document.writeln("myFish before: " + myFish);
pushed = myFish.push("drum", "lion");
document.writeln("myFish after: " + myFish);
document.writeln("pushed this element last: " + pushed);
This example displays the following:

myFish before: ["angel", "clown"]
myFish after: ["angel", "clown", "drum", "lion"]
pushed this element last: 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

Navigator 3.0, LiveWire 1.0

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

Navigator 4.0, Netscape Server 3.0

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

Navigator 4.0, Netscape Server 3.0

Syntax

slice(begin,end)

Parameters

begin
Zero-based index at which to begin extraction.

end
(Optional) Zero-based index at which to end extraction:

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:

Object references (and not the actual object) -- slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Strings and numbers (not String and Number objects)-- slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

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

splice

Changes the content of an array, adding new elements while removing old elements.

Method of

Array

Implemented in

Navigator 4.0, Netscape Server 3.0

Syntax

splice(index, howMany, newElt1, ..., newEltN)

Parameters

index
Index at which to start changing the array.

howMany
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element.

newElt1, ..., newEltN
(Optional) The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.

Description

If you specify a different number of elements to insert than the number you're removing, the array will have a different length at the end of the call.

If howMany is 1, this method returns the single element that it removes. If howMany is more than 1, the method returns an array containing the removed elements.

Examples

The following script illustrate the use of splice:

<SCRIPT LANGUAGE="JavaScript1.2">
myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish: " + myFish + "<BR>");
removed = myFish.splice(2, 0, "drum");
document.writeln("After adding 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(3, 1)
document.writeln("After removing 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(2, 1, "trumpet")
document.writeln("After replacing 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(0, 2, "parrot", "anemone", "blue")
document.writeln("After replacing 2: " + myFish);
document.writeln("removed is: " + removed);
</SCRIPT>
This script displays:

myFish: ["angel", "clown", "mandarin", "surgeon"]
After adding 1: ["angel", "clown", "drum", "mandarin", "surgeon"]
removed is: undefined
After removing 1: ["angel", "clown", "drum", "surgeon"]
removed is: mandarin
After replacing 1: ["angel", "clown", "trumpet", "surgeon"]
removed is: drum
After replacing 2: ["parrot", "anemone", "blue", "trumpet", "surgeon"]
removed is: ["angel", "clown"]

sort

Sorts the elements of an array.

Method of

Array

Implemented in

Navigator 3.0, LiveWire 1.0
Navigator 4.0: modified behavior.

Syntax

sort(compareFunction)

Parameters

compareFunction
Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

Description

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

So, the compare function has the following form:

function compare(a, b) {
   if (a is less than b by some ordering criterion)
      return -1
   if (a is greater than b by the ordering criterion)
      return 1
   // a must be equal to b
   return 0
}
To compare numbers instead of strings, the compare function can simply subtract b from a:

function compareNumbers(a, b) {
   return a - b
}
JavaScript uses a stable sort: the index partial order of a and b does not change if a and b are equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b move due to sorting.

The behavior of the sort method changed between Navigator 3.0 and Navigator 4.0. In Navigator 3.0, on some platforms, the sort method does not work. This method works on all platforms for Navigator 4.0.

In Navigator 4.0, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array. For example, assume you have this script:

<SCRIPT>
a = new Array();
a[0] = "Ant";
a[5] = "Zebra";
function writeArray(x) {
   for (i = 0; i < x.length; i++) {
      document.write(x[i]);
      if (i < x.length-1) document.write(", ");
   }
}
writeArray(a);
a.sort();
document.write("<BR><BR>");
writeArray(a);
</SCRIPT>
In Navigator 3.0, JavaScript prints:

ant, null, null, null, null, zebra 
ant, null, null, null, null, zebra
In Navigator 4.0, JavaScript prints:

ant, undefined, undefined, undefined, undefined, zebra 
ant, zebra, undefined, undefined, undefined, undefined

Examples

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

<SCRIPT>
stringArray = new Array("Blue","Humpback","Beluga")
numericStringArray = new Array("80","9","700")
numberArray = new Array(40,1,5,200)
mixedNumericArray = new Array("80","9","700",40,1,5,200)
function compareNumbers(a, b) {
   return a - b
}
document.write("<B>stringArray:</B> " + stringArray.join() +"<BR>")
document.write("<B>Sorted:</B> " + stringArray.sort() +"<P>")
document.write("<B>numberArray:</B> " + numberArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + numberArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + numberArray.sort(compareNumbers) +"<P>")
document.write("<B>numericStringArray:</B> " + numericStringArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + numericStringArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + numericStringArray.sort(compareNumbers) +"<P>")
document.write("<B>mixedNumericArray:</B> " + mixedNumericArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + mixedNumericArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + mixedNumericArray.sort(compareNumbers) +"<BR>")
</SCRIPT>
This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback
numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200
numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700
mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

See also

Array.join, Array.reverse

toString

Returns a string representing the specified object.

Method of

Array

Implemented in

Navigator 3.0, LiveWire 1.0

Syntax

toString()

Parameters

None.

Description

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

For Array objects, the built-in toString method joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and uses toString to convert the array to a string while writing output.

var monthNames = new Array("Jan","Feb","Mar","Apr")
document.write("monthNames.toString() is " + monthNames.toString())
The output is as follows:

monthNames.toString() is Jan,Feb,Mar,Apr
For information on defining your own toString method, see the Object.toString method.

unshift

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

Method of

Array

Implemented in

Navigator 4.0, Netscape Server 3.0

Syntax

arrayName.unshift(elt1,..., eltN)

Parameters

elt1,...,eltN
The elements to add to the front of the array.

Example

The following code displays the myFish array before and after adding elements to it.

myFish = ["angel", "clown"];
document.writeln("myFish before: " + myFish);
unshifted = myFish.unshift("drum", "lion");
document.writeln("myFish after: " + myFish);
document.writeln("New length: " + unshifted);
This example displays the following:

myFish before: ["angel", "clown"]
myFish after: ["drum", "lion", "angel", "clown"]
New length: 4

See also

pop, push, shift


[Contents] [Previous] [Next] [Index]

Last Updated: 10/31/97 16:00:33


Copyright ?1997 Netscape Communications Corporation