Array
object constructor:
new Array(arrayLength)An array literal:
new Array(element0, element1, ..., elementN)
[element0, element1, ..., elementN]JavaScript 1.2 when you specify
LANGUAGE="JavaScript1.2"
in the <SCRIPT>
tag:
new Array(element0, element1, ..., elementN)
arrayLength | |
elementN |
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.
length
property (size of the array) set to the integer. The array initially contains no elements, even though it might have a non-zero length.musicTypes = new Array(25)When you specify a single parameter with the
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
Array
constructor in JavaScript 1.2, the behavior depends on whether you specify LANGUAGE="JavaScript1.2"
in the <SCRIPT>
tag:
LANGUAGE="JavaScript1.2"
in the <SCRIPT>
tag, a single-element array is returned. For example, new Array(5)
creates a one-element array with the first element being 5. A constructor with a single parameter acts in the same way as a multiple parameter constructor. You cannot specify the length
property of an Array
using a constructor with one parameter.LANGUAGE="JavaScript1.2"
in the <SCRIPT>
tag, you specify the initial length of the array as with other JavaScript versions.colors = new Array()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
colors[99] = "midnightblue"
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:
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]
.
watch
and unwatch
methods from Object
.
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()Example 2: Two-dimensional array. The following code creates a two-dimensional array and assigns the results to
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."
myVar
.
myVar="Multidimensional array test; "This example assigns the following string to
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 +"; "
}
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(arrayName2, arrayName3, ..., arrayNameN)
arrayName2... |
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:
concat
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.String
and Number
objects): concat
copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other arrays.alpha=new Array("a","b","c")The following code concatenates three arrays:
numeric=new Array(1,2,3)
alphaNumeric=alpha.concat(numeric) // creates array ["a","b","c",1,2,3]
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]
Object.constructor
.
join(separator)
separator |
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
Array.reverse
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.
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() {The following example shortens the array
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
}
}
}
statesUS
to a length of 50 if the current length is greater than 50.
if (statesUS.length > 50) {
statesUS.length=50
}
pop()
myFish
array containing four elements, then removes its last element.
myFish = ["angel", "clown", "mandarin", "surgeon"];
popped = myFish.pop();
push
, shift
, unshift
Function.prototype
.push(element1, ..., elementN)
element1, ..., |
push
method is analogous to the push
function in Perl 4. Note that this behavior is different in Perl 5.
myFish
array containing two elements, then adds two elements to it. After the code executes, pushed
contains "lion".
myFish = ["angel", "clown"];
pushed = myFish.push("drum", "lion");
pop
, shift
, unshift
reverse()
reverse
method transposes the elements of the calling array object.
myArray
, containing three elements, then reverses the array.
myArray = new Array("one", "two", "three")This code changes
myArray.reverse()
myArray
so that:
Array.join
, Array.sort
shift()
myFish
array before and after removing its first element. It also displays the removed element:
myFish = ["angel", "clown", "mandarin", "surgeon"];This example displays the following:
document.writeln("myFish before: " + myFish);
shifted = myFish.shift();
document.writeln("myFish after: " + myFish);
document.writeln("Removed this element: " + shifted);
myFish before: ["angel", "clown", "mandarin", "surgeon"]
myFish after: ["clown", "mandarin", "surgeon"]
Removed this element: angel
pop
, push
, unshift
slice(begin[,end])
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:
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.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.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(compareFunction)
compareFunction |
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:
compareFunction(a, b)
is less than 0, sort b
to a lower index than a
.compareFunction(a, b)
returns 0, leave a
and b
unchanged with respect to each other, but sorted with respect to all different elements.compareFunction(a, b)
is greater than 0, sort b
to a higher index than a
.function compare(a, b) {To compare numbers instead of strings, the compare function can simply subtract b from a:
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
}
function compareNumbers(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
return a - b
}
sort
method changed between JavaScript 1.1 and
JavaScript 1.2.
In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.
In JavaScript 1.2, 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);In JavaScript 1.1, JavaScript prints:
a.sort();
document.write("<BR><BR>");
writeArray(a);
</SCRIPT>
ant, null, null, null, null, zebraIn JavaScript 1.2, JavaScript prints:
ant, null, null, null, null, zebra
ant, undefined, undefined, undefined, undefined, zebra
ant, zebra, undefined, undefined, undefined, undefined
<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>")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.
document.write("<B>Sorted without a compare function:</B> " + mixedNumericArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + mixedNumericArray.sort(compareNumbers) +"<BR>")
</SCRIPT>
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
Array.join
, Array.reverse
splice(index, howMany, [element1][, ..., elementN])
index | |
howMany | |
element1, ..., |
splice
method returns the element removed, if only one element is removed (howMany
parameter is 1); otherwise, splice
returns an array containing the removed elements.
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"]
toString()
Array
object overrides the toString
method of Object
. For Array
objects, the 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.
var monthNames = new Array("Jan","Feb","Mar","Apr")JavaScript calls the
myVar=monthNames.toString() // assigns "Jan,Feb,Mar,Apr" to myVar
toString
method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
In JavaScript 1.2 when you specify LANGUAGE="JavaScript1.2"
in the <SCRIPT> tag, toString
returns a string representing the source code of the array.
<SCRIPT LANGUAGE="JavaScript1.2">
var monthNames = new Array("Jan","Feb","Mar","Apr")
myVar=monthNames.toString() // assigns '["Jan", "Feb", "Mar", "Apr"]'
// to myVar
</SCRIPT>
arrayName.unshift(element1,..., elementN)
element1,..., |
myFish
array before and after adding elements to it.
myFish = ["angel", "clown"];This example displays the following:
document.writeln("myFish before: " + myFish);
unshifted = myFish.unshift("drum", "lion");
document.writeln("myFish after: " + myFish);
document.writeln("New length: " + unshifted);
myFish before: ["angel", "clown"]
myFish after: ["drum", "lion", "angel", "clown"]
New length: 4
pop
, push
, shift
valueOf()
Array
object inherits the valueOf
method of Object
. The valueOf
method of Array
returns the primitive value of an array or the primitive value of its elements as follows:
Object type of element |
Data type of returned value
|
|
| |
---|
Object.valueOf
Last Updated: 11/13/98 10:22:45
Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use