Array is collection of similar type of elements. We can use concept of array to make program more readable, easy to handle large data and implementing concept of loops in program. With the help of array the size of code is also decrease. When we allocate memory to objects in array then allocation of element in memory is continuous. Array is used in static data structure to represents data in memory. In this demonstration we learn how to implement array in java script.
Creating an array object
var fruitCollection = new Array();
Initializing values in Array Object
An example which demonstrate use of Array Object
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function arrayDemo() {
//Creating an array object.
var fruitCollection = new Array();
//Initilizing value to an array object.
fruitCollection = ["Mango", "Pine Apple", "Apple", "Orange"];
//Accessing value of fruitCollection array
document.write("First Value In FruitCollection : " + fruitCollection[0] + "<br />");
document.write("Next Value In FruitCollection : " + fruitCollection[1] + "<br />");
document.write("Next Value In FruitCollection : " + fruitCollection[2] + "<br />");
document.write("Last Value In FruitCollection : " + fruitCollection[3] + "<br />");
//Calculating length of fruitArray collecting by
//calling length method of array object.
document.write("Length of the FruitCollection array is : " + fruitCollection.length + "<br />");
//Retriving value of fruitCollection array by using loop.
document.write("Retriving value of fruitArray collection by using loop.<br />");
for (count = 0; count < fruitCollection.length; count++) {
document.write(fruitCollection[count] + "<br />");
}
}
</script>
</head>
<body>
<input type="button" value="Click this to view message" onclick="arrayDemo()" />
</body>
</html>
Output of the following code snippet is as follows


Leave Comment