Home Java Javascript-array How to Print Array in JavaScript
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

How to Print Array in JavaScript

Advertisement
This tutorial will helps you to find how to declare array and print an array in JavaScript.

How to Print Array in JavaScript

In this section you will learn about Array in JavaScript. Array are important part of all programming languages. Array in JavaScript is a variable that can hold more than one value. Array is a collection of data item. Each element of array can store its own data. Element of array can be added and removed at any time and its value can also be changed. The important feature of array is that it can hold different type of data.

You can create an Array in different ways as follows :

1.var mycity=new Array(); 
  mycity[0]="Delhi";       
  mycity[1]="Agra";
  mycity[2]="Jaipur";

2. var mycity = new Array("Delhi", "Agra", "Jaipur");

3. var mycity = ["Delhi", "Agra", "Jaipur"];

Access an Array :

By index you can access the array. To access the array you can write it as follows:

var a=myCity[0];

This statement access the first element of array. If you want to change the value of array then

mycity[0]="Bangalore";

There are some methods of array that can use in array like length() can find the length of array.

var b=mycity.length // Number of element in the array
var c=mycity.indexOf["Agra"]//return the index of Agra

Now, here is the example how to declare and access array.

<!DOCTYPE html>
<html>
<script>function arraycreation()
{
var mycity = new Array(5);
mycity[0]="Delhi";
mycity[1]="Agra";
mycity[2]="Merrut";
mycity[3]="Bangalore";
mycity[4]="Pune";
for(var i=0;i<mycity.length;i++){
document.write("<b>mycity["+i+"] is </b>=>"+mycity[i]+"<br>");
}
}
</script>
<body bgcolor="EECFE#"><h1>Java Script Array example</h1><p><h2>Click to print the array element</h2></p><p><input type="button" value="Click" onclick="arraycreation()"> </input></p></p></body>
</html>

When you execute this program output will be as follows:

When user click on the button , it will display the content of an array.

Download Source Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 6, 2013

Ask Questions?    Discuss: How to Print Array in JavaScript  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com