The Array object is used to store a set of values in a single variable name. You can define an Array object with the new keyword.
The following line of code defines an Array object called myArray.
var myArray=new Array()
You can also define the array size by passing an integer argument as follows.
var myArray=new Array(5)
You can add the values to an array as the following.
var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"
You can also give values to the arrays while defining it as below.
var myArray=new Array("value1", "value2", "value3")
While 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 line accesses the first value of the array myArray.
document.write(myArray[0])
Read Also: How to Load External JavaScript Asynchronously or Dynamically
Table of Contents
Loop Through JavaScript Array
You can loop any Array by using any of the following looping statements in JavaScript.
Using For loop
For loop is a basic looping structure. You can loop any Array by using For Loop as below.
var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"
for(i=0; i<myArray.length;i++){
document.write(myArray[i])
}
Example:
<script type="text/javascript">
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
for(i=0; i<mycars.length;i++){
document.write(mycars[i]+"<br/>")
}
</script>
Preview:
Read Also: How to Validate an HTML Form Using JavaScript?
Using For… In Statement
There is another looping statement “For…In” statement similar to for loop. You can loop any Array by using “For… In” Statement as below.
var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"
for(x in myArray){
document.write(myArray[x])
}
Example:
<script type="text/javascript">
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
for(x in mycars){
document.write(mycars[x]+"<br/>")
}
</script>
Preview:
Read Also: How to create Changeable Date and Time Using JavaScript?
Do … while loops
You can also loop any Array by using another looping statement do … while loops as the given below.
var myArray=new Array()
var i=0
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"
do{
document.write(myArray[x])
i++;
}
while(i<myArray.length)
Example:
<script type="text/javascript">
var mycars=new Array()
var i=0
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
do{
document.write(mycars[i]+"<br/>")
i++;
}
while(i<mycars.length)
</script>
Preview:
Read Next: How to Concatenate, Join and Sort Array in JavaScript?