The function of an array object is to use a separate variable name to store a series of values.
Create an array and assign a value to it:
Example
var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW";
What is an array?
An array object uses a separate variable name to store a series of values.
If you have a set of data (for example: car name), there are individual variables as follows:
var car1="Saab"; var car2="Volvo"; var car3="BMW";
However, what if you want to find a certain car from it? And not 3 cars, but 300 cars? This will not be an easy task!
The best way is to use arrays.
An array can store all values with a variable name, and any value can be accessed with a variable name.
Each element in the array has its own ID so that it can be easily accessed.
Create an array
There are three ways to create an array.
The following code defines an array object named myCars:
1: General way:
var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW";
2: Simple way:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];
Accessing an array
By specifying the array name and index number, you can access a specific element.
The following instance can access the first value of the myCars array:
var name=myCars[0];
The following example modifies the first element of the array myCars:
myCars[0]="Opel";
lamp [0] is the first element of the array. [1] is the second element of the array.
In an array you can have different objects
All JavaScript variables are objects. Array elements are objects. Functions are objects.
So you can have different variable types in the array.
You can include object elements, functions, and arrays in an array:
myArray[0]=; myArray[1]=myFunction; myArray[2]=myCars;
Array methods and properties
Predefined properties and methods using array objects:
var x= // the number of elements in myCars var y=("Volvo") // the index position of "Volvo"
Create a new method
The prototype is a JavaScript global constructor. It can build properties and methods of new Javascript objects.
Example: Create a new method.
=function() { for (i=0;i<;i++) {this[i]=this[i].toUpperCase();} }
The example above creates a new array method for converting lowercase characters into uppercase characters.