Home  • Programming • JavaScript

JavaScript One Dimensional Array

One Dimensional Array Declaration:
var myCar=[]
or
var myCar=new Array()
One Dimensional Array Initialization:
myCar[0]="Chev";
myCar[1]="Ford";
myCar[2]="Buick";
myCar[3]="Lincoln";
myCar[4]="Truck";
One Dimensional Array Literal Declaration
var myCar=["Chev","Ford","Buick","Lincoln","Truck"];
or
var myCar=new Array("Chev","Ford","Buick","Lincoln","Truck");
Read and Write one dimensional array 1. Read:
   document.write(myCar[3]); //Using 3 index number it will print Lincoln
   document.write(myCar[0]);// Using 0 index it will print first item: Chev
   document.write(myCar[myCar.length-1]); //Using (myCar.length-1)=>(5-1)=>4, it will print last item: Truck
2. Write:
  myCar[2]="BMW"; // it will replace "Buick" item with "BMW"
  myCar[0]="TATA"; // it will replace "Chev" item with "TATA"
  myCar[myCar.length-1]="Van"; //it will replace "Truck" item with "Van"
Iterate One Dimensional Array through for loop, while loop and do-while loop 1. Iterate through for loop:
 for(i=0;i<myCar.length;i++){
    document.write(myCar[i]);
 }

 for(var i in myCar){
   document.write(myCar[i]);
}
2. Iterate through while loop:
  var i=0;
  while(i<myCar.length){   
   document.write(myCar[i]);
   i++;
  }
3. Iterate through do-while loop:
var i=0;
do{
  document.write(myCar[i]);
  i++;
}while(i<myCar.length)

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd