Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Friday, 26 June 2015

JavaScript array is an object that represents a collection of similar type of elements. We can create array in javascript. There are 3 ways to construct array in JavaScript
1.    By array literal
2.    By creating instance of Array directly (using new keyword)
3.    By using an Array constructor (using new keyword)

1.      JavaScript array literal

Syntax:


var arrayname=[value1,value2.....valueN];  

Values are contained inside [ ] and separated by , (comma).
Example of creating and using Array:

The .length property returns the length of an array.
<script> 
            var Student=["Vishal","Ankit","Anish"]; 
            for (i=0;i< Student.length;i++){ 
document.write(Student[i] + "<br/>"); 
            } 
</script>

Output :
Vishal
Ankit
Anish

2.     JavaScript Array directly (new keyword)

Syntax:  

var arrayname=new Array();  

Here, new keyword is used to create instance of array.
Example:
  <script>
      var i;
      var emp = new Array();
      emp[0] = "Anish";
      emp[1] = "Ajay";
      emp[2] = "Anuj";

      for (i = 0; i < emp.length; i++) {
          document.write(emp[i] + "<br>");
      } 
</script> 

Output :

Anish
Ajay
Anuj

3.     JavaScript array constructor (new keyword)
In this method, we need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitely.

Example:

<script>
    var emp = new Array("Anuj", "Akhil", "Abhay");
    for (i = 0; i < emp.length; i++) {
        document.write(emp[i] + "<br>");
    } 
</script> 

Output :

Anuj
Akhil
Abhay
Categories: ,

0 comments:

Post a Comment