Thursday 13 February 2014

Handling array in javascript

The Array object lets you store multiple values in a single variable. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


var arr = new Array( "Jon", "XXX", "Kit" );

The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array.

You can retrive array using indexs like arr[0], arr[1].
 
Splice Method:
Javascript array slice() method extracts a section of an array and returns a new array. It returns the extracted array based on the passed parameters.
 
Array.splice(startIndex,ItemToRemove,items);

It will add or remove to or from array as per requirement.
var fruits = ["Chair", "Table", "Mat"];
fruits.splice(2,0,"Glass","Bottle");

Output will be:["Chair", "Table", "Glass","Bottle","Mat"]

Unshift method: 

Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

syntex:
array.unshift( element1, ..., elementN );

 You can find below example to get it more clearly:

<html>
   <head>
      <title>JavaScript Array unshift Method</title>
   </head>
   
   <body>
   
      <script type="text/javascript">
         var arr = new Array("orange", "mango", "banana", "sugar");
         
         var length = arr.unshift("water");
         document.write("Returned array is : " + arr );
         document.write("<br /> Length of the array is : " + length );
      </script>
      
   </body>
</html>

Hope it helps you.  I will come up with more ideas in future.

 

No comments:

Post a Comment