Core JavaScript 1.5 Reference:Global Objects:Array
From MDC
Contents |
Summary
Lets you work with arrays.
Syntax
var arr1 = new Array(arrayLength); var arr2 = new Array(element0, element1, ..., elementN);
Array literals use the form:
var lit = [element0, element1, ..., elementN];
Parameters
-
arrayLength - The initial length of the array. You can access this value using the length property. If the value specified is not a number, an array of length 1 is created, with the first element having the specified value. The maximum length allowed for an array is 4,294,967,295.
-
elementN - A value for the element in that position in the array. When this form is used, the array is initialized with the specified values as its elements, and the array's length property is set to the number of arguments.
Description
An array is an ordered set of values associated with a single variable name. Note that you shouldn't use it as an associative array, use Object instead.
The following example creates an Array object with an array literal; the coffees array contains three elements and has a length of three:
var coffees = ["Kenyan", "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:
var 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:
var myArray = new Array("Wind", "Rain", "Fire");
You can then refer to the elements as thus:
-
myArray[0]is the first element -
myArray[1]is the second element -
myArray[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:
var 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:
var 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.
var 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
var myRe = /d(b+)(d)/i;
var 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 |
Properties
For properties inherited by Array instances, see Properties of Array instances.
- prototype
- Allows the addition of properties to all objects.
Properties inherited from Function.prototype
caller, constructor, length, name
Methods
For methods inherited by Array instances, see Methods of Array instances.
Although the global Array object contains no methods of its own, it does inherit some methods through the prototype chain.
Methods inherited from Object.prototype
__defineGetter__, __defineSetter__, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, unwatch, watch
Array instances
Array instances inherit from Array.prototype. As with all constructors, you can change the constructor's prototype object to make changes to all Array instances.
Properties
- constructor
- Specifies the function that creates an object's prototype.
- index
- This is pseudo-property of
Arrayprototypes because it is not inherited by default. It is, in fact, only present in arrays created by regular expression matches. The property represents the zero-based index of the match in the string. - input
- This property is only present in arrays created by regular expression matches. It reflects the original string against which the regular expression was matched.
- length
- Reflects the number of elements in an array.
Methods
Mutator methods
These methods modify the array:
- pop
- Removes the last element from an array and returns that element.
- push
- Adds one or more elements to the end of an array and returns the new length of the array.
- reverse
- Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
- shift
- Removes the first element from an array and returns that element.
- sort
- Sorts the elements of an array.
- splice
- Adds and/or removes elements from an array.
- unshift
- Adds one or more elements to the front of an array and returns the new length of the array.
Accessor methods
These methods do not modify the array and return some representation of the array.
- concat
- Returns a new array comprised of this array joined with other array(s) and/or value(s).
- join
- Joins all elements of an array into a string.
- slice
- Extracts a section of an array and returns a new array.
- toSource
- Non-standard
- Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.prototype.toSource method.
- toString
- Returns a string representing the array and its elements. Overrides the Object.prototype.toString method.
Introduced in JavaScript 1.6
- indexOf
- Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
- lastIndexOf
- Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Iteration methods
Introduced in JavaScript 1.6
Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.
- filter
- Creates a new array with all of the elements of this array for which the provided filtering function returns true.
- forEach
- Calls a function for each element in the array.
- every
- Returns true if every element in this array satisfies the provided testing function.
- map
- Creates a new array with the results of calling a provided function on every element in this array.
- some
- Returns true if at least one element in this array satisfies the provided testing function.
Introduced in JavaScript 1.8
- reduce
- Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
- reduceRight
- Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Methods inherited from Object.prototype
__defineGetter__, __defineSetter__, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, unwatch, valueOf, watch
Examples
Example: 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";
if (msgArray.length == 100)
print("The length is 100.");
Example: Creating a Two-dimensional Array
The following creates chess board as a two dimensional array of strings. The first move is made by copying the 'P' in 1,4 to 3,4. The position 1,4 is left blank.
var board =
[ ['R','N','B','Q','K','B','N','R'],
['P','P','P','P','P','P','P','P'],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
['p','p','p','p','p','p','p','p'],
['r','n','b','q','k','b','n','r']];
print(board.join('\n') + '\n\n');
// Move King's Pawn forward 2
board[3][4] = board[1][4];
board[1][4] = ' ';
print(board.join('\n'));
Here is the output:
R,N,B,Q,K,B,N,R P,P,P,P,P,P,P,P , , , , , , , , , , , , , , , , , , , , , , , , , , , , p,p,p,p,p,p,p,p r,n,b,q,k,b,n,r R,N,B,Q,K,B,N,R P,P,P,P, ,P,P,P , , , , , , , , , , ,P, , , , , , , , , , , , , , , , , p,p,p,p,p,p,p,p r,n,b,q,k,b,n,r