Array Object Overview
The Array object is used to store multiple values in a single variable.
Creating an Array Object
To create an Array object, use the new keyword and assign the result to a variable.
The following examples show the different ways to create Array objects:
var myArray = new Array();
myArray[0] = "Red";
myArray[1] = "Blue";
myArray[2] = "Green";
or
var myArray = new Array("Red", "Blue", "Green");
or
var myArray = ["Red", "Blue", "Green"];
Accessing Elements in an Array Object
To access an element within an Array object, referring to the name of the array and the index number. The index number starts at 0.
The following example shows how to access an element within an Array object:
var favoriteColor = myArray[1];
Modifying Elements in an Array Object
To modify a value in an existing array, just add a new value to the array with a specified index number:
The following example shows how to modify an element within an Array object:
myArray[1] = "Yellow";
Properties
Property | Description |
---|---|
constructor |
Returns the function that created the object's prototype |
length |
Sets or returns the number of elements in an array |
prototype |
Allows you to add properties and methods to an object |
Methods
Method | Description |
---|---|
concat() |
Joins two or more arrays, and returns a copy of the joined arrays |
join() |
Joins all elements of an array into a string |
pop() |
Removes the last element of an array, and returns that element |
push() |
Adds new elements to the end of an array, and returns the new length |
reverse() |
Reverses the order of the elements in an array |
shift() |
Removes the first element of an array, and returns that element |
slice() |
Selects a part of an array, and returns the new array |
sort() |
Sorts the elements of an array |
splice() |
Adds/Removes elements from an array |
toString() |
Converts an array to a string, and returns the result |
unshift() |
Adds new elements to the beginning of an array, and returns the new length |
valueOf() |
Returns the primitive value of an array |