[Contents] [Previous] [Next] [Last]


Chapter 7
The Array Object

This section describes the new features and changes for arrays.

Creating Arrays With Literal Notation

In addition to creating an array using its constructor function, you can create it using literal notation.

Syntax

arrayName = [element0, element1, ..., elementn]

Properties

arrayName is the name of the new array.

elementn is 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 is set to the number of arguments.

Description

You do not have to specify all elements in the new array. If you put 2 commas in a row, the array will be created with spaces for the unspecifed elements, as shown in the second example.

If an array is created using literal notation in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Example

The following example creates the coffees array with three elements and a length of three:

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

The following example creates the fish array, with 2 prespecified elements and one empty element:

fish = ["Lion", , "Surgeon"]

With this expression fish[0] is "Lion", fish[2] is "Surgeon", and fish[1] is undefined.

Methods

concat

Core method. Joins two arrays and returns a new array.

Syntax

arrayName1.concat(arrayName2)

Parameters

arrayName1 is the name of the first array.

arrayName2 is the name of the second array.

Method of

Array object

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.

pop

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

Syntax

arrayName.pop()

Parameters

arrayName is the name of an array.

Method of

Array object.

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

push

Core method. Adds one or more elements to the end of an array and returns the last element added. This method changes the length of the array. (Note: This is analagous to the behavior of push in Perl 4. In Perl 5, push returns the new length of the array.)

Syntax

arrayName.push(elt1,..., eltN)

Parameters

arrayName is the name of an array.

elt1,...,eltN are the elements to add to the end of the array.

Method of

Array object

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

shift

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

Syntax

arrayName.shift()

Parameters

arrayName is the name of an array.

Method of

Array object.

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

unshift

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

Syntax

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

Parameters

arrayName is the name of an array.

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

Method of

Array object

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

slice

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

Syntax

arrayName.slice(beginSlice,[endSlice])

Parameters

arrayName is the name of an array.

beginSlice is the zero-based index at which to begin extraction.

endSlice is the zero-based index at which to end extraction.

Method of

Array object

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 are aware of 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 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

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

Syntax

arrayName.splice(index, howMany, [newElt1, ..., newEltN])

Parameters

arrayName is the name of an array.

index is the index at which to start changing the array.

howMany is 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 are the elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.

Method of

Array object

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

Core method. sort now works on all platforms. It no longer converts undefined elements to null, and it sorts them to the high end of the array. For example:

<SCRIPT LANGUAGE="JavaScript1.2">
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>

JavaScript in Navigator 3 prints:

ant, null, null, null, null, zebra

ant, null, null, null, null, zebra

JavaScript in Navigator 4 prints:

ant, undefined, undefined, undefined, undefined, zebra

ant, zebra, undefined, undefined, undefined, undefined

Creating Arrays Under JavaScript 1.2

If you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag, using new Array(1) creates a new array with a[0]=1.

Without the LANGUAGE="JavaScript1.2" specification, new Array(1) sets the array's length to 1 and a[0] to undefined.

Example

The following example prints 1. Without LANGUAGE="JavaScript1.2", it prints undefined.

<SCRIPT LANGUAGE="JavaScript1.2">
a=new Array(1);
document.write(a[0] + "<BR>");
</SCRIPT>

Working With Arrays and Regular Expressions

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace.

Syntax

arrayName.propertyName
arrayName[element0,..., elementn]

Parameters

arrayName is the name of the array.

propertyName is one of the properties listed below.

elementn is one of the elements listed below.

Properties and Elements

To help explain the 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 a match between a regular expression and a string are as follows (the examples are a result of the above script):

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

Description

The returned array varies depending on the type of match that was executed. The following lists shows what is returned if the match is successful. (regexp is a regular expression, str is a string, and replaceText is the replacement text for the replace method.

regexp.exec(str) returns:

An array containing the match string, any parenthesized substring matches, and the input and index properties as described above.

str.match(regexp) returns:

An array containing the match string, the last parenthesized substring match (if included), and the input and index properties as described above.

str.match(regexp) where regexp includes the global flag (e.g. /abc/g) returns:

An array of all matches and the last parenthesized substring match (if included). input and index are undefined.

str.match(regexp) where regexp includes the global and ignore case flags (e.g. /abc/gi) returns:

An array of all matches. input and index are undefined.

str.replace(regexp, "replaceText") returns:

A string with the regular expression match replaced by replaceText. input and index are undefined.


[Contents] [Previous] [Next] [Last]

Last Updated: 10/22/97 11:48:07


Copyright © 1997 Netscape Communications Corporation