Mozilla.com


Array

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 literal 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 literal number, an array of length 1 is created, with the first element having the specified value.
  • If the value specified is a number object (e.g., created with "new Number(123)"), then it will, unlike literal numbers, be treated as an array of length 1 with the first element being the number object.

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:
arity, caller, constructor, length, name

Methods

For methods inherited by Array instances, see Methods of Array instances.

Methods inherited from Function:
apply, call, toSource, toString

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 Array prototypes 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.
indexOf Requires JavaScript 1.6
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
lastIndexOf Requires JavaScript 1.6
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

Iteration methods

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 Requires JavaScript 1.6
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
forEach Requires JavaScript 1.6
Calls a function for each element in the array.
every Requires JavaScript 1.6
Returns true if every element in this array satisfies the provided testing function.
map Requires JavaScript 1.6
Creates a new array with the results of calling a provided function on every element in this array.
some Requires JavaScript 1.6
Returns true if at least one element in this array satisfies the provided testing function.
reduce Requires JavaScript 1.8
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
reduceRight Requires JavaScript 1.8
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

Generic methods

Many methods on the JavaScript Array object are designed to be generally applied to all objects which "look like" Arrays. That is, they can be used on any object which has a length property, and which can usefully be accessed using numeric property names (as with array[5] indexing). Some methods, such as join, only read the length and numeric properties of the object they are called on. Others, like reverse, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like String, which does not permit its length property or synthesized numeric properties to be set.

Introduced in JavaScript 1.6

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 6,4 to 4,4. The position 4,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[4][4] = board[6][4];
board[6][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

Page last modified 06:20, 12 Mar 2010 by Sevenspade

Tags:

Files (0)