JavaScript Array object
JavaScript Array (array) object
What is an array?
Array objects use separate variable names to store a series of values.
If you have a set of data (for example: car name), there are separate variables as follows:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to find a certain car? And not 3 cars, but 300 cars? This will not be an easy task!
The best way is to use an array.
Arrays can store all values with one variable name, and any value can be accessed with 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 ways to create an array.
The following code defines an array object named myCars:
1: Conventional method:
var myCars=new Array();
myCars[0 = new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];
Accessing Array
You can access a specific element by specifying the array name and index number.
The following example 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";
[0] is the first element of the array. [1] is the second element of the array.
You can have different objects in an array
All JavaScript variables are objects. Array elements are objects. Functions are objects.
So, you can have different variable types in the array.
You can contain object elements, functions, and arrays in an array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
Array methods and properties
Using arrays Object predefined properties and methods:
var x=myCars.length
Use the for...in statement to loop through the elements in the output array:
How to use the concat() method to merge two arrays:
How to use The sort() method literally sorts an array:
How to use the sort() method to numerically sort an array: