Browser/User Agent Support
| IE | Mozilla | Netscape | Opera | Safari | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
|---|
Constructors
| Constructor | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Constructs a new instance of an array. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Properties
| Property | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Specifies the function that creates the Array prototype. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Zero-based index number for the corresponding string in a RegExp match. | no | 1.0+ | 3.0+ | 7.0+ | no |
String in a RegExp match. | no | 1.0+ | 3.0+ | 7.0+ | no |
Integer specifying the number of elements in an array. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Represents the Array prototype object. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Methods
| Method | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Returns a new array comprised of this array joined
with other array(s) and/or value(s).
| 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns true if every element in an array meets the specified criteria. | no | 1.0+ | 3.0+ | no | no |
Creates a new array with all elements that meet the specified criteria. | no | 1.0+ | 3.0+ | no | no |
Executes the specified function once for each element in an array. | no | 1.0+ | 3.0+ | no | no |
Returns the first index number at which the specified element can be found in the array. Returns -1 if the element is not present. | no | 1.0+ | 3.0+ | no | no |
Joins all elements of an array into a string. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Searches an array backwards starting from fromIndex and returns the last index number at which the specified element can be found in the array. Returns -1 if the element is not present. | no | 1.0+ | 3.0+ | no | no |
Creates a new array with the results of calling a provided function on every element in this array. | no | 1.0+ | 3.0+ | no | no |
Removes the last element from an array and returns
that element. This method changes the length of the
array.
| 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
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.
| 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Transposes the elements of an array: the first array
element becomes the last and the last becomes the
first.
| 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Removes the first element from an array and returns
that element. This method changes the length of the
array.
| 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Extracts a section of an array and returns a new
array.
| 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns true if some element in the array passes the test implemented by the provided function. | no | 1.0+ | 4.0+ | no | no |
Sorts the elements of an array. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Returns the array with the specified elements inserted or removed. | 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns a localized string version of the array. | 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns a string representing the source code of the array. | no | 1.0+ | 3.0+ | no | no |
Returns a string representing the specified array and
its elements.
| 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Adds one or more elements to the beginning of an array
and returns the new length of the array.
| 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns the primitive value of an array or the primitive value of its elements. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Creating an Array
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.
var 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.";
Creating a Two-dimensional Array
The following creates a two-dimensional array and
assigns the results to myVar.
var myVar = "Multidimensional array test; ";
a = new Array(4);
for (var i = 0; i < 4; i++) {
a[i] = new Array(4);
for (var j = 0; j < 4; j++) {
a[i][j] = "[" + i + "," + j + "]";
}
}
for (var i = 0; i < 4; i++) {
str = "Row " + i + ":";
for (var j = 0; j < 4; j++) {
str += a[i][j];
}
myVar += str + "; ";
}The following string is assigned 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];
Remarks
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 has 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 can then refer to the elements as thus:
myArray[0]is the first elementmyArray[1]is the second elementmyArray[2]is the third element
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.
- If the value specified is a number, the constructor converts the number to an unsigned, 32-bit integer and generates an array with the 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.
- If the value specified is not a number, an array of length 1 is created, with the first element having the specified value.
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:
// 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");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 |
Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Constructor Detail
Array Array(Number arrayLength, Number elementN)
Constructs a new instance of an array.
| Number | 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. |
| Number | 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. (zero-or-more) |
- Throws
- Throws RangeError if arrayLength is negative or is larger than 232-1.
Property Detail
Object constructor
Specifies the function that creates the Array prototype.
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Number index
Zero-based index number for the corresponding string in a RegExp match.
- Remarks
- Only applicable to an array created by a RegExp match.
- Availability
JavaScript 1.2
String input
String in a RegExp match.
- Remarks
- Only applicable to an array created by a RegExp match.
- Availability
JavaScript 1.2
Number length
Integer specifying the number of elements in an array.
-
Iterating over an array
In the following example, the
getChoicefunction uses thelengthproperty to iterate over every element in themusicTypearray.musicTypeis a select element on themusicFormform.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 } } }Shortening an array
The following example shortens the array
statesUSto a length of 50 if the current length is greater than 50.if (statesUS.length > 50) { statesUS.length=50 } - Remarks
-
The value of the
lengthproperty is an integer with a positive sign and a value less than 2 to the 32 power (232).You can set the
lengthproperty to truncate an array at any time. When you extend an array by changing itslengthproperty, the number of actual elements does not increase; for example, if you setlengthto 3 when it is currently 2, the array still contains only 2 elements. - Availability
JavaScript 1.1, JScript 2.0 | ECMAScript v1
Object prototype
Represents the Array prototype object.
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Method Detail
concat(Number valueN) : Array
Returns a new array comprised of this array joined with other array(s) and/or value(s).
| Number | valueN | Arrays and/or values to concatenate to this array. (one-or-more) |
-
Concatenating two arrays
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]Concatenating three arrays
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]
Concatenating values to an array
The following code concatenates three values to an array:
alpha = ['a', 'b', 'c']; alphaNumeric = alpha.concat(1, 2, 3); // creates array ["a", "b", "c", 1, 2, 3]
- Remarks
-
concatdoes 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:- Object references (and not the actual object):
concatcopies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
- Strings and numbers (not String
and Number
objects):
concatcopies the values of strings and numbers into the new array.
Any operation on the new array will have no effect on the original arrays, and vice versa.
- Object references (and not the actual object):
- See Also
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
every(Function callback, Function thisObject) : Boolean
Returns true if every element in an array meets the specified criteria.
| Function | callback | Function that tests each element of an array. |
| Function | thisObject | Object to use as this when executing callback. (zero-or-more) |
Example: Testing size of all array elements
The following example tests whether all elements in the array are bigger than 10.
function isBigEnough(element, index, array) { return (element >= 10); } passed = [12, 5, 8, 130, 44].every(isBigEnough); // passed is false passed = [12, 54, 18, 130, 44].every(isBigEnough); // passed is true- Remarks
everyexecutes the provided function (callback) once for each element present in the array until it finds one wherecallbackreturns a false value. If such an element is found, the test aborts andfalseis returned, otherwise (callbackreturned a true value for each of the elements)everywill returntrue. Arrays are treated as "dense", meaning thatcallbackwill be invoked for each index less than the array'slength, even if a given index has never been explicitly assigned.callbackis invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.If a
thisObjectparameter is provided toevery, it will be used as thethisfor each invocation of thecallback. If it is not provided, or isnull, the global object associated withcallbackis used instead.everydoes not mutate the array on which it is called.The range of elements processed by
everyis set before the first invocation ofcallback. Elements which are appended to the array after the call toeverybegins will not be visited bycallback. If existing elements of the array are changed, or deleted, their value as passed tocallbackwill be the value at the timeeveryvisits them; elements that are deleted will have the valueundefined.- Availability
JavaScript 1.5 | Gecko 1.8b2
filter(Function callback, Function thisObject) : Array
Creates a new array with all elements that meet the specified criteria.
| Function | callback | Function that tests each element of an array. |
| Function | thisObject | Object to use as this when executing callback. (zero-or-more) |
Example: Filtering out all small values
The following example uses
filterto create a filtered array that has all elements with values less than 10 removed.function isBigEnough(element, index, array) { return (element >= 10); } filtered = [12, 5, 8, 130, 44].filter(isBigEnough);- Remarks
filtercalls a providedcallbackfunction once for each element in an array, and constructs a new array of all the values for whichcallbackreturns a true value. The produced array is dense; values which do not pass thecallbacktest are simply skipped, and are not assigned an index in the new array.callbackis invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.If a
thisObjectparameter is provided tofilter, it will be used as thethisfor each invocation of thecallback. If it is not provided, or isnull, the global object associated withcallbackis used instead.filterdoes not mutate the array on which it is called.The range of elements processed by
filteris set before the first invocation ofcallback. Elements which are appended to the array after the call tofilterbegins will not be visited bycallback. If existing elements of the array are changed, or deleted, their value as passed tocallbackwill be the value at the timefiltervisits them; elements that are deleted will have the valueundefined.- Availability
JavaScript 1.5 | Gecko 1.8b2
forEach(Function callBack, Object thisObject) : Object
Executes the specified function once for each element in an array.
| Function | callBack | Function to call once on each array element. |
| Object | thisObject | Object to use as this when executing callback. (zero-or-more) |
Example: Printing the contents of an array
The following code prints a line for each element in an array (and presumes the presence of a
printfunction to call!):function printElt(element, index, array) { print("[" + index + "] is " + element); } [2, 5, 9].forEach(printElt); // Prints: // [0] is 2 // [1] is 5 // [2] is 9Example: Printing the contents of an array with an object method
The following code creates a simple writer object and then uses the
writelnmethod to write one line per element in the array. (This presumes the presence of aprintfunction to call!):var writer = { sb: [], write: function (s) { this.sb.push(s); }, writeln: function (s) { this.write(s + "\n"); }, toString: function () { return this.sb.join(""); } }; [2, 5, 9].forEach(writer.writeln, writer); print(writer.toString()); // Prints: // 2 // 5 // 9- Remarks
forEachexecutes the provided function (callback) once for each element present in the array. Arrays are treated as "dense", meaning thatcallbackwill be invoked for each index less than the array'slength, even if a given index has never been explicitly assigned.callbackis invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.If a
thisObjectparameter is provided toforEach, it will be used as thethisfor each invocation of thecallback. If it is not provided, or isnull, the global object associated withcallbackis used instead.forEachdoes not mutate the array on which it is called.The range of elements processed by
forEachis set before the first invocation ofcallback. Elements which are appended to the array after the call toforEachbegins will not be visited bycallback. If existing elements of the array are changed, or deleted, their value as passed tocallbackwill be the value at the timeforEachvisits them; elements that are deleted will have the valueundefined.- Availability
JavaScript 1.5 | Gecko 1.8b2
indexOf([Object searchElement,] [Number fromIndex]) : Number
Returns the first index number at which the specified element can be found in the array. Returns -1 if the element is not present.
| Object | searchElement | Element to search for in the array. (optional) |
| Number | fromIndex | Index number to begin searching the array. Default is 0, which searches the whole array. (optional) |
Example: Using indexOf
The following example uses
indexOfto locate values in an array.array = [2, 5, 9]; index = array.indexOf(2); // index is 0 index = array.indexOf(7); // index is -1
Example: Finding all the occurrences of an element
The following example uses
indexOfto find all the indices of an element in a given array, usingpushto add them to another array as they are found.indices = []; idx = array.indexOf(element) while (idx != -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); }- Remarks
indexOfcomparessearchElementto elements of the Array using strict equality (the same method used by the triple-equals (===) operator).For the
fromIndexparameter, if the specifiedfromIndexis greater than or equal to the length of the array,lastIndexOfdoes not search the array and returns -1. If the specifiedfromIndexis negative, the search start position is the offset from the back end of the array; however, the array is still searched from front to back.- See Also
- Availability
JavaScript 1.5 | Gecko 1.8b2
join([String separator]) : String
Joins all elements of an array into a string.
| String | 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 sparated with a comma. (optional) |
-
Joining an array three different ways
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 myVar2 myVar3=a.join(" + ") // assigns "Wind + Rain + Fire" to myVar3 - Remarks
-
The string conversions of all array elements are joined into one string.
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
lastIndexOf([Object searchElement,] [Number fromIndex]) : Number
Searches an array backwards starting from fromIndex and returns the last index number at which the specified element can be found in the array. Returns -1 if the element is not present.
| Object | searchElement | Element to search for in the array. (optional) |
| Number | fromIndex | Index number to begin searching the array backwards from. Default is the last element in the array, which searches the whole array. (optional) |
-
Example: Using lastIndexOf
The following example uses
lastIndexOfto locate values in an array.array = [2, 5, 9, 2]; index = array.lastIndexOf(2); // index is 3 index = array.lastIndexOf(7); // index is -1 index = array.lastIndexOf(2, 3); // index is 3 index = array.lastIndexOf(2, 2); // index is 0 index = array.lastIndexOf(2, -2); // index is 0 index = array.lastIndexOf(2, -1); // index is 3
Example: Finding all the occurrences of an element
The following example uses
lastIndexOfto find all the indices of an element in a given array, usingpushto add them to another array as they are found.indices = []; idx = array.lastIndexOf(element) while (idx != -1) { indices.push(idx); idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); }Note that we have to handle the case
idx == 0separately here because the element will always be found regardsless thefromIndexparameter if it is the first element of the array. This is different from theindexOfmethod. - Remarks
indexOfcomparessearchElementto elements of the Array using strict equality (the same method used by the triple-equals (===) operator).For the
fromIndexparameter, if the specifiedfromIndexis greater than or equal to the length of the array,lastIndexOfdoes not search the array and returns -1. If the specifiedfromIndexis negative, the search start position is the offset from the start of the array; however, the array is still searched from back to front.- See Also
- Availability
JavaScript 1.5 | Gecko 1.8b2
map(Function callBack, Object thisObject) : Array
Creates a new array with the results of calling a provided function on every element in this array.
| Function | callBack | Function that creates an element of the new Array from an element of the current one. |
| Object | thisObject | Object to use as this when executing callback. (zero-or-more) |
Example: Upper-casing the strings in an array
The following code creates a new array which contains upper-case versions of all the strings in the original.
strings = ["hello", "Array", "WORLD"]; function makeUpperCase(v) { return v.toUpperCase(); } uppers = strings.map(makeUpperCase); // uppers is now ["HELLO", "ARRAY", "WORLD"] // strings is unchangedExample: Mapping an array of numbers to an array of square roots
The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
numbers = [1, 4, 9]; roots = numbers.map(Math.sqrt); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]
- Remarks
mapcalls a providedcallbackfunction once for each element in an array, in order, and constructs a new array from the results. Arrays are treated as "dense", meaning thatcallbackwill be invoked for each index less than the array'slength, even if a given index has never been explicitly assigned.callbackis invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.If a
thisObjectparameter is provided tomap, it will be used as thethisfor each invocation of thecallback. If it is not provided, or isnull, the global object associated withcallbackis used instead.mapdoes not mutate the array on which it is called.The range of elements processed by
mapis set before the first invocation ofcallback. Elements which are appended to the array after the call tomapbegins will not be visited bycallback. If existing elements of the array are changed, or deleted, their value as passed tocallbackwill be the value at the timemapvisits them; elements that are deleted will have the valueundefined.- Availability
JavaScript 1.5 | Gecko 1.8b2
pop() : Object
Removes the last element from an array and returns that element. This method changes the length of the array.
-
Removing the last element of an array
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
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
push(Object element1, ..., elementN) : Number
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.
| Object | element1, ..., elementN | The elements to add to the end of the array. (one-or-more) |
-
Adding elements to an array
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"); - Remarks
-
The behavior of the
pushmethod is analogous to thepushfunction in Perl 4 (not Perl 5). - See Also
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
reverse() : Array
Transposes the elements of an array: the first array element becomes the last and the last becomes the first.
-
Reversing the elements in an array
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
myArrayso that:myArray[0]is "three"myArray[1]is "two"myArray[2]is "one"
- Remarks
-
The
reversemethod transposes the elements of the calling array object. - See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
shift() : Object
Removes the first element from an array and returns that element. This method changes the length of the array.
-
Removing an element from an array
The following code displays the
myFisharray 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
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
slice(Object begin, Object end) : Array
Extracts a section of an array and returns a new array.
| Object | begin | Zero-based index at which to begin extraction. |
| Object | end | Zero-based index at which to end extraction. slice extracts up to but not including end. |
-
Using
sliceIn the following example,
slicecreates a new array,newCar, frommyCar. Both include a reference to the objectmyHonda. When the color ofmyHondais changed to purple, both arrays reflect the change.//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>")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 - Remarks
-
slicedoes 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:- For object references (and not the actual object),
slicecopies 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.
- For strings and numbers (not String
and Number
objects),
slicecopies 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.
- For object references (and not the actual object),
- See Also
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
some([Object searchElement,] [Number fromIndex]) : Boolean
Returns true if some element in the array passes the test implemented by the provided function.
| Object | searchElement | Element to search for in the array. (optional) |
| Number | fromIndex | Index number to begin searching the array backwards from. Default is the last element in the array, which searches the whole array. (optional) |
Example: Testing size of all array elements
The following example tests whether some element in the array is bigger than 10.
function isBigEnough(element, index, array) { return (element >= 10); } passed = [2, 5, 8, 1, 4].some(isBigEnough); // passed is false passed = [12, 5, 8, 1, 44].some(isBigEnough); // passed is true- Remarks
someexecutes the provided function (callback) once for each element present in the array until it finds one wherecallbackreturns a true value. If such an element is found, the test aborts andtrueis returned, otherwise (callbackreturned a false value for each of the elements)somewill returnfalse. Arrays are treated as "dense", meaning thatcallbackwill be invoked for each index less than the array'slength, even if a given index has never been explicitly assigned.callbackis invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.If a
thisObjectparameter is provided tosome, it will be used as thethisfor each invocation of thecallback. If it is not provided, or isnull, the global object associated withcallbackis used instead.somedoes not mutate the array on which it is called.The range of elements processed by
someis set before the first invocation ofcallback. Elements that are appended to the array after the call tosomebegins will not be visited bycallback. If an existing, unvisited element of the array is changed or deleted bycallback, its value passed to the visitingcallbackwill be the value at the time thatsomevisits that element's index; elements that are deleted before being visited will have the valueundefined.- Availability
JavaScript 1.5 | Gecko 1.8b2
sort([Function compareFunction]) : Array
Sorts the elements of an array.
| Function | 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. (optional) |
-
Creating, displaying, and sorting an array
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.
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("stringArray: " + stringArray.join() +"<BR>") document.write("Sorted: " + stringArray.sort() +"<P>") document.write("numberArray: " + numberArray.join() +"<BR>") document.write("Sorted without a compare function: " + numberArray.sort() +"<BR>") document.write("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"<P>") document.write("numericStringArray: " + numericStringArray.join() +"<BR>") document.write("Sorted without a compare function: " + numericStringArray.sort() +"<BR>") document.write("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"<P>") document.write("mixedNumericArray: " + mixedNumericArray.join() +"<BR>") document.write("Sorted without a compare function: " + mixedNumericArray.sort() +"<BR>") document.write("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"<BR>")This example shows that when you use a compare function, the elements are sorted 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
- Remarks
-
If
compareFunctionis 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
compareFunctionis supplied, the array elements are sorted according to the return value of the compare function. Ifaandbare two elements being compared, then:- If
compareFunction(a, b)is less than 0, sortbto a lower index thana.
- If
compareFunction(a, b)returns 0, leaveaandbunchanged with respect to each other, but sorted with respect to all different elements.
- If
compareFunction(a, b)is greater than 0, sortbto a higher index thana.
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
bfroma:function compareNumbers(a, b) { return a - b }JavaScript uses a stable sort: the index partial order of
aandbdoes not change ifaandbare equal. Ifa's index was less thanb's before sorting, it will be after sorting, no matter howaandbmove due to sorting.The behavior of the
sortmethod changed between JavaScript 1.1 and JavaScript 1.2.In JavaScript 1.1, on some platforms, the
sortmethod 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:
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);In JavaScript 1.1, JavaScript prints:
ant, null, null, null, null, zebra ant, null, null, null, null, zebra
In JavaScript 1.2, JavaScript prints:
ant, undefined, undefined, undefined, undefined, zebra ant, zebra, undefined, undefined, undefined, undefined
- If
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
splice(Object index, [Number howMany,] Object element1, ..., elementN) : Array
Returns the array with the specified elements inserted or removed.
| Object | index | Index at which to start changing the array. |
| Number | 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. (optional) |
| Object | element1, ..., elementN | The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. (zero-or-more) |
-
Using
spliceThe following script excerpt illustrates the use of splice:
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);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"]
- Remarks
-
If you insert a different number of elements than you remove, the array will have a different length at the end of the call.
The
splicemethod returns an array containing the removed elements. If you remove only one element,splicereturns one element. - See Also
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
toLocaleString() : String
Returns a localized string version of the array.
- Throws
- Throws TypeError if toLocaleString is called on an object that is not an array.
- See Also
- Availability
JavaScript 1.5 | JScript 5.5 | ECMAScript v1
toSource() : String
Returns a string representing the source code of the array.
Example: Examining the source code of an array
To examine the source code of an array:
alpha = new Array("a", "b", "c") alpha.toSource() //returns ["a", "b", "c"]- Remarks
-
The
toSourcemethod returns the following values:- For the built-in
Arrayobject,toSourcereturns the following string indicating that the source code is not available:
function Array() { [native code] }- For instances of
Array,toSourcereturns a string representing the source code.
This method is usually called internally by JavaScript and not explicitly in code. You can call
toSourcewhile debugging to examine the contents of an array. - For the built-in
- See Also
- Availability
JavaScript 1.3
toString() : String
Returns a string representing the specified array and its elements.
- Remarks
-
The Array object overrides the
toStringmethod of Object. For Array objects, thetoStringmethod joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and usestoStringto convert the array to a string.var monthNames = new Array("Jan","Feb","Mar","Apr") myVar=monthNames.toString() // assigns "Jan,Feb,Mar,Apr" to myVarJavaScript calls the
toStringmethod automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. - Throws
- Throws TypeError if toString is called on an object that is not an array.
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
unshift(Object element1, ..., elementN) : Number
Adds one or more elements to the beginning of an array and returns the new length of the array.
| Object | element1, ..., elementN | The elements to add to the front of the array. (one-or-more) |
-
Adding elements to an array
The following code displays the
myFisharray 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
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
valueOf() : BooleanNumberString
Returns the primitive value of an array or the primitive value of its elements.
- Remarks
-
The table below displays how the data type of an array corresponds to the data type returned by the valueOf method.
Data type of array element Return type Boolean Boolean Number or Date Number All other object types String - See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
