Thursday, June 28, 2012

Java Script Tutorial 22 : JavaScript Array Object


An array is a special variable, which can hold more than one value, at a time. For example, if you have a list of items, storing the country names in single variables could look like as follow :


var country1="Pakistan";
var country2="USA";
var country3="Russia";


An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own ID so that it can be easily accessed. We can defined array in following ways :


var country=new Array(); 
country[0]="Pakistan";
country[1]="USA";
country[2]="Russia";


or


var country=new Array("Pakistan","USA","Russia");


or


var country=["Pakistan","USA"," Russia"];


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. For example


document.write(country[1]);


Result of above code will be : USA


To modify a value in an existing array, just add a new value to the array with a specified index number:


country[1]="Germany";


This code change the value USA to Germany inside array object.


document.write(country[0]);


Now It will result as : Germany


No comments:

Post a Comment