Arrays in Java script

Discussion in 'JavaScript and AJAX' started by Sanskruti, Apr 18, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India
    Arrays are one way of keeping a program more organized. They allow you to do some things that are difficult without them. Arrays are usually a group of the same variable type that use an index number to distinguish them from each other. Suppose you wanted to write out 5 names, and use variables for each one of the names. You could define 5 variables:
    Code:
    name[0]="Peter"; 
    name[1]="Alex."; 
    name[2]="James."; 
    name[3]="Jones"; 
    name[4]="Michael."; 
    
    However, a better way may be to use an array. To define an array, we need to follow the following form:

    var Name_of_Array= new Array(number_of_elements);

    Name_of_Array would be the name you want to give the array variable, the number_of_elements is the number of variables you want the array to store. So, for our names, we could write:

    Code:
    var name= new Array(5); 
    Now, to assign values, we are going to use what is called an index number, and place it inside brackets. We attach this right on the end of the word name, so our first name would be:

    Code:
    name[0] 
    I know, zero instead of 1. Arrays just work that way, the first element is always zero and the last element is always one less than what you define as the number of elements. In this case, our first element is name[0], the last is name[4]. So to assign the values we had, we could use a straight assignment, like this:
    Code:
    var name= new Array(5) 
    name[0]="Peter"; 
    name[1]="Alex."; 
    name[2]="James."; 
    name[3]="Jones"; 
    name[4]="Michael."; 
    Notice that when we do this, we leave off the semicolon at the end of the array definition, and use semicolons at the end of each element we define. So far, it has only made things more complicated. However, this array can now be used as part of a loop, using the value of the index numbers as a variable:

    Code:
    var x=0; 
    for (x=0; x<5; x++) 
    { 
      alert(name[x]); 
    } 
    
    This uses the variable x in place of each index number, and runs the alert for all 5 elements in our array. The first time through, you would get an alert with name[0], the second time, name[1], and so on..

    x++ means that we add one to the value of x. In a similar fashion, we can subtract one from x with x--. This is how we are able to go from x being 0 to x being equal to 4. It stops at 4 because part of the condition is that the loop is only run while x is less than 5. So the last time it runs, x is equal to 5 and it does not go any further.

    HTML:
    <HTML>
      <HEAD> 
        <SCRIPT language="JavaScript"> 
        <!-- 
          function display_name() 
          { 
            var name= new Array(5) 
            name[0]="Peter."; 
            name[1]="Alex"; 
            name[2]="James."; 
            name[3]="John"; 
            name[4]="Micheal"; 
            var x=0; 
            for (x=0; x<5; x++) 
            { 
              alert(name[x]); 
            } 
          } 
        //-->
        </SCRIPT> 
      </HEAD> 
      <BODY> 
        <A HREF="javascript:display_name()">Names of Friends</A> 
      </BODY> 
    </HTML>
    You could also assign the values of the array using a loop. This would allow the viewer to assign the values using prompts, and then you could alert them with their own words!

    Code:
    var name = new Array(5); 
    var y=0; 
    for (y=0; y<5; y++) 
    { 
      name[y]=prompt('Enter a Name!',' '); 
    } 
    Notice that we just defined the array, without assigning initial values. Don't forget the semicolon! Then we get the values by letting the viewer enter them through a prompt. name[y] uses the value of y each time it is run. So, you are assigning name[0] the first time, name[1] the second time, and so on. The complete script is below
    HTML:
    <HTML>
      <HEAD> 
        <SCRIPT language="JavaScript"> 
        <!-- 
          function display_name2() 
          { 
            var name= new Array(5); 
            var y=0; 
            for (y=0; y<5; y++) 
            { 
              name[y]=prompt('Enter a name!',' '); 
            } 
            var x=0; 
            for (x=0; x<5; x++) 
            { 
              alert(name[x]); 
            } 
          } 
        //-->
        </SCRIPT> 
      </HEAD> 
      <BODY> 
        <A HREF="javascript:display_name2()">Name of friends</A> 
      </BODY> 
    </HTML>
    Associative arrays give you another way to store information. Using associative arrays, you can call the array element you need using a string rather than a number, which is often easier to remember. The downside is that these aren't as useful in a loop because they do not use numbers as the index value. An associative array is defined just like a regular array, but we insert some text in the place we had numbers in the regular arrays:

    Code:
    var my_cars= new Array()
    my_cars["cool"]="Zen";
    my_cars["family"]="Tata Safari";
    my_cars["big"]="Scorpio";
    Now we can get the Word Zen later in the script by remembering it is the "cool" car, so we would use my_cars["cool"]. This could be used to prompt a user to input the type of car he/she would prefer. Then you can send back what you think the viewer should buy based on the input:

    HTML:
    <HTML>
      <HEAD> 
        <SCRIPT language="JavaScript">
        <!--
        function which_car()
        {
          var my_cars= new Array()
          my_cars["cool"]="Zen";
          my_cars["family"]="Tata Safari";
          my_cars["big"]="Scorpio";
          var car_type=prompt("What type of car do you like?","");
          if ((car_type=="cool") || (car_type=="family") || (car_type=="big"))
            alert("I think you should get a "+my_cars[car_type]+".");
          else
            alert("I don't really know what you should get. Sorry.");
        }
        //-->
        </SCRIPT>
      </HEAD> 
      <BODY> 
        <FORM>
          <INPUT TYPE="button" onClick="which_car()" value="Go!">
        </FORM>
      </BODY> 
    </HTML>
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    You can also initialize an array like this,
    Code:
    var name = ['Pradeep','Shabbir','Sanskruti'];
    
    Associative arrays can be declared in JavaScript Object Notation
    Code:
    var cars = {cool: 'Zen', family: 'Tata Safari', big: 'Scorpia'};
    
     
  3. rekha11

    rekha11 New Member

    Joined:
    Jan 31, 2008
    Messages:
    13
    Likes Received:
    3
    Trophy Points:
    0
    " Array is a group of similer datatypes "
    A simple example of a single- dimensioned array is:
    myArray = new Array(14,82,40,6,25)

    A Simple example of two-dimensioned array is:
    Array[0, 0]:= "Tom" Array[0, 1]:= "scientist" Array[1, 0]:= "Beryl" Array[1, 1]:= "engineer" Array[2, 0]:= "Ann" Array[2, 1]:= "surgeon" Array[3, 0]:= "Bill" Array[3, 1]:= "taxman" Array[4, 0]:= "Myrtal" Array[4, 1]:= "bank robber"
     
  4. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0
    Arrays in JavaScript are extremely useful for storing and manipulating information you have coded directly into the script, or information collected from the browser. In this article, Dan Wellman details how to use and manipulate them.
    The array is one of a number of objects built directly into JavaScript. Think of them simply as variables containing multiple values. They can hold string or numerical values, have no maximum boundaries (although the speed at which your scripts are interpreted will decrease as the amount of data increases) and are comma delimited. They have no persistence, meaning that their values are not held once the page containing the script has closed or reloaded.

    The aim of this article is to show you how information can be hard-coded into your scripts and how that information can be addressed and used to enhance your Web pages. The example script will focus just on one dimensional arrays.

    Single Dimensioned Arrays

    A simple example of a single-dimensioned array is:

    myArray = new Array(15,89,4,61,5)

    Which simply says create an array called myArray with five values, the values are integers and equal 15, 89, 4, 61 and 5. This information, were it to mean anything, could then be manipulated in all kinds of ways; you could print the results on the page using the simple command:

    document.write(myArray[1])

    That would display 15 on the page. You could also perform simple math, were the need to arise:

    var mySum = myArray[1] * myArray[2]
    document.write(mySum)

    which displays the number 356.

    An important property of the array object is the length property; the extremely basic numerical array above has a length of five. Each of the values in the array can be accessed using their index within square brackets following the array name, for example:

    myArray[2]

    It’s important to remember that the indices of any array always begin with 0 representing the first item in the array; therefore, while the length property of this very simple array is five, the highest index is four.
     
  5. Full Zip Hoody

    Full Zip Hoody New Member

    Joined:
    Sep 29, 2010
    Messages:
    20
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programer
    Location:
    US of A
    in deed the best way to keep you program organized is by using the arrays
     
  6. benivolentsoft

    benivolentsoft New Member

    Joined:
    Feb 2, 2011
    Messages:
    21
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.benivolent.com/
    Thank you for the script and ideas given..
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice