JavaScript Array Object

previous next


The Array object is used to store a set of values in a single variable name.


Defining Arrays

The Array object is used to store a set of values in a single variable name.

We define an Array object with the new keyword. The following code line defines an Array object called myArray:

var myArray = new Array()

There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).

way 1:

var city = new Array()
city[0]="Casablanca"
city[1]="Rabat"
city[2]="Agadir"
city[3]="Khouribga"

You could also pass an integer argument to control the array's size:

var city = new Array(4)
city[0]="Casablanca"
city[1]="Rabat"
city[2]="Agadir"
city[3]="Khouribga"

way 2:

var city = new Array("Casablanca","Rabat","Agadir","Khouribga")

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.


Accessing Arrays

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:

document.write(city[3])

will result in the following output:

Khouribga

 


Modify Values in Existing Arrays

To modify a value in an existing array, just add a new value to the array with a specified index number:

city[1] = "Marrakech"

Now, the following code line:

document.write(city[1])

will result in the following output:

Marrakech

 


Array Object Methods

Method

Description

concat() Joins two or more arrays and returns the result
join() Puts all the elements of an array into a string. The elements are separated by a specified delimiter
pop() Removes and returns the last element of an array
push() Adds one or more elements to the end of an array and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes and returns the first element of an array
slice() Returns selected elements from an existing array
sort() Sorts the elements of an array
splice() Removes and adds new elements to an array
toSource() Represents the source code of an object
toString() Converts an array to a string and returns the result
unshift() Adds one or more elements to the beginning of an array and returns the new length
valueOf() Returns the primitive value of an Array object

 


Array Object Properties

Property

Description

constructor A reference to the function that created the object
length Sets or returns the number of elements in an array
prototype Allows you to add properties and methods to the object

 


Try it

To see how HTML and JavaScript work, you can only push the submit button, or you can make your own HTML and JavaScript code.

           

 


previous next