How to work with Javascipt Array


Array is a very powerful concept in any programming language. It can strore same or any kind of object data in its elements.
In his post I tried to venture my learning on storing and displaying array elements in Javascript.
Storing a javascript array elements can be divided into two parts..



Static:

<SCRIPT language = "JavaScript">
<!-- Begin Hiding JavaScript
cities = new Array(5);
cities[0] = "Hyderabad";
cities[1] = "Kolkata";
cities[2] = "Delhi";
cities[3] = "Mumbai";
cities[4] = "Panaji";
</script>


Dynamic:


<SCRIPT language = JavaScript>
         var elements= prompt("Enter How Many elements", "Elements");
         cities = new Array(elements);
 for(var i=0;i<=(elements-1);i++)
{   
   var cities[i]= prompt("Enter your city Name", "City");
}
 </SCRIPT>

Now to display those elements there are 3 ways:
One traditional for loop--
first find out the length of the array---

len=cities.length();
for(i=0;i<=len-1;i++)
{
document.write(cities[i]+"<BR>");
}


Second method could be more static


document.write(cities[0]+"<BR>");
document.write(cities[1]+"<BR>");
document.write(cities[2]+"<BR>");
document.write(cities[3]+"<BR>");
document.write(cities[4]+"<BR>");



The Third method could be---


join_crit =  cities.join();
document.write(join_crit);

I like this method to display all the elements of an array.

How to work with Javascipt Array How to work with Javascipt Array Reviewed by Animesh Chatterjee on February 23, 2012 Rating: 5

No comments:

Powered by Blogger.