JavaScript ArrayObject
The role of the array object is: to use a single variable name to store a series of values.
Online Examples
Create an array, assign values to it:
Example
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
Try it yourself »
At the bottom of the page you can find more examples.
What is an Array?
An array object uses a single variable name to store a series of values.
If you have a set of data (for example: car names), stored in separate variables as shown below:
var car2="Volvo";
var car3="BMW";
However, if you want to find a particular car from them? And not 3 cars, but 300? That would not be an easy task!
The best way is to use an array.
An array can store all values with one variable name, and you can access any value using the variable name.
Each element in the array has its own ID so that it can be easily accessed.
Create an Array
There are three methods to create an array.
The following code defines an array object named myCars:
1: Conventional way:
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Concise way:
3: Literal:
Access an Array
By specifying the array name and the index number, you can access a specific element.
The following example accesses the first value of the myCars array:
The following example modifies the first element of the array myCars:
You can have different objects in an array
All JavaScript variables are objects. Array elements are objects. Functions are objects.
Therefore, you can have different variable types in an array.
You can include object elements, functions, and arrays in an array:
myArray[1]=myFunction;
myArray[2]=myCars;
Array Methods and Properties
Use the predefined properties and methods of the array object:
var y=myCars.indexOf("Volvo") // the index of the "Volvo" value
Complete Array Object Reference Manual
You can refer to the complete reference manual on this site for all properties and methods of arrays.
The reference manual contains descriptions of all properties and methods (and more examples).
Complete Array Object Reference Manual
Creating New Methods
Prototype is a JavaScript global constructor. It can build properties and methods for new JavaScript objects.
Example: Create a new method.
for (i=0;i<this.length;i++){
this[i]=this[i].toUpperCase();
}
}
Try it yourself »
The above example creates a new array method for converting lowercase characters in an array to uppercase characters.
More Examples
Combine array elements into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetical ascending) - sort()
Numeric sorting (numeric ascending) - sort()
Numeric sorting (numeric descending) - sort()
Add an element at position 2 in an array - splice()
Other Extensions