Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Examples Using Arrays - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Arrays

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Examples Using Arrays - JavaScript(JS)

This section presents several examples of creating and manipulating arrays.

Examples Using Arrays

 

This section presents several examples of creating and manipulating arrays.

 

Creating and Initializing Arrays

The script in Fig. 10.3 uses operator new to allocate an Array of five elements and an emp-ty array. The script demonstrates initializing an Array of existing elements and also shows that an Array can grow dynamically to accommodate new elements. The Array’s values are displayed in XHTML tables.

 

Line 17 creates Array n1 as an array of five elements. Line 18 creates Array n2 as an empty array. Lines 21–22 use a for statement to initialize the elements of n1 to their sub-

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 10.3: InitArray.html -->

 

      <!-- Initializing the elements of an array. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Initializing an Array</title>

 

        <style type = "text/css">

 

        table { width: 10em }

              th   { text-align: left }

 

        </style>

 

        <script type = "text/javascript">

        <!--

 

        // create (declare) two new arrays

 

        var n1 = new Array( 5 ); // allocate five-element Array

 

        var n2 = new Array(); // allocate empty Array

        // assign values to each element of Array n1

        for ( var i = 0; i < n1.length; ++i )

                     n1[ i ] = i;

        // create and initialize five elements in Array n2

                     for ( i = 0; i < 5; ++i )

                     n2[ i ] = i;

        outputArray( "Array n1:", n1 );

 

        outputArray( "Array n2:", n2 );

 

        // output the heading followed by a two-column table

 

        // containing subscripts and elements of "theArray"

 

        function outputArray( heading, theArray )

{

document.writeln(    "<h2>" + heading + "</h2>" );

document.writeln(    "<table border = \"1\"" );

document.writeln(    "<thead><th>Subscript</th>" +

"<th>Value</th></thead><tbody>" );                   

                                   

// output the subscript and value of each array element

for ( var i = 0; i < theArray.length;  i++ )   

                       

document.writeln( "<tr><td>" + i + "</td><td>" +

theArray[ i      ] + "</td></tr>" );

        document.writeln( "</tbody></table>" );

 

        } // end function outputArray

// -->

      </script>

 

      </head><body></body>

 

</html>


Fig. 10.3 | Initializing the elements of an array

script numbers (0 to 4). Note also the use of zero-based counting (remember, array sub-scripts start at 0) so that the loop can access every element of the array. Note too the use of the expression n1.length in the condition for the for statement to determine the length of the array. In this example, the length of the array is 5, so the loop continues executing as long as the value of control variable i is less than 5. For a five-element array, the sub-script values are 0 through 4, so using the less than operator, <, guarantees that the loop does not attempt to access an element beyond the end of the array. Zero-based counting is usually used to iterate through arrays.

 

Lines 25–26 use a for statement to add five elements to the Array n2 and initialize each element to its subscript number (0 to 4). Note that Array n2 grows dynamically to accommodate the values assigned to each element of the array.

Lines 28–29 invoke function outputArray (defined in lines 33–46) to display the contents of each array in an XHTML table. Function outputArray receives two argu-ments—a string to be output before the XHTML table that displays the contents of the array and the array to output. Lines 41–43 use a for statement to output XHTML text that defines each row of the table. Once again, note the use of zero-based counting so that the loop can access every element of the array.

If the values of an Array’s elements are known in advance, the elements can be allo-cated and initialized in the declaration of the array. There are two ways in which the initial values can be specified. The statement

 

 

var n = [ 10, 20, 30, 40, 50 ];

 

uses a comma-separated initializer list enclosed in square brackets ([ and ]) to create a five-element Array with subscripts of 0, 1, 2, 3 and 4. The array size is determined by the num-ber of values in the initializer list. Note that the preceding declaration does not require the new operator to create the Array object—this functionality is provided by the interpreter when it encounters an array declaration that includes an initializer list. The statement

 

var n = new Array( 10, 20, 30, 40, 50 );

 

also creates a five-element array with subscripts of 0, 1, 2, 3 and 4. In this case, the initial values of the array elements are specified as arguments in the parentheses following new Array. The size of the array is determined by the number of values in parentheses. It is also possible to reserve a space in an Array for a value to be specified later by using a comma as a place holder in the initializer list. For example, the statement

 

var n = [ 10, 20, , 40, 50 ];

 

creates a five-element array with no value specified for the third element (n[ 2 ]).

 

Initializing Arrays with Initializer Lists

The script in Fig. 10.4 creates three Array objects to demonstrate initializing arrays with initializer lists (lines 18–20) and displays each array in an XHTML table using the same function outputArray discussed in Fig. 10.3. Note that when Array integers2 is dis-played in the web page, the elements with subscripts 1 and 2 (the second and third ele-ments of the array) appear in the web page as undefined. These are the two elements for which we did not supply values in the declaration in line 20 in the script.

 

Summing the Elements of an Array with for and forin

The script in Fig. 10.5 sums the values contained in theArray, the 10-element integer ar-ray declared, allocated and initialized in line 13. The statement in line 19 in the body of the first for statement does the totaling. Note that the values supplied as initializers for array theArray could be read into the program using an XHTML form.

In this example, we introduce JavaScript’s forin statement, which enables a script to perform a task for each element in an array (or, as we will see in Chapters 12–13, for each element in a collection). This process is also known as iterating over the elements of an array. Lines 25-26 show the syntax of a forin statement. Inside the parentheses, we declare the element variable used to select each element in the object to the right of key-

 

 

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 10.4: InitArray2.html -->

 

      <!-- Declaring and initializing arrays. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Initializing an Array with a Declaration</title>

 

        <style type = "text/css">

 

        table { width: 15em }

              th   { text-align: left }

 

        </style>

 

        <script type = "text/javascript">

        <!--

 

        // Initializer list specifies the number of elements and

 

        // a value for each element.

 

        var colors = new Array( "cyan", "magenta","yellow", "black" );

 

        var integers1 = [ 2, 4, 6, 8 ];

 

        var integers2 = [ 2, , , 8 ];

        outputArray( "Array colors contains", colors );

 

        outputArray( "Array integers1 contains", integers1 );

 

        outputArray( "Array integers2 contains", integers2 );

 

        // output the heading followed by a two-column table

 

        // containing the subscripts and elements of theArray

 

        function outputArray( heading, theArray )

{

document.writeln(    "<h2>" + heading + "</h2>" );

document.writeln(    "<table border = \"1\"" );

document.writeln(    "<thead><th>Subscript</th>" +

"<th>Value</th></thead><tbody>" );       

                       

// output the subscript and value of each array element

for ( var i = 0; i < theArray.length;  i++ )

document.writeln( "<tr><td>" + i + "</td><td>" +

theArray[ i      ] + "</td></tr>" );       

        document.writeln( "</tbody></table>" );

 

        } // end function outputArray

        // -->

 

        </script>

 

        </head><body></body>

 

</html>


Fig. 10.4 | Declaring and initializing arrays.

 

    <?xml version = "1.0" encoding = "utf-8"?>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 10.5: SumArray.html -->

 

    <!-- Summing elements of an array. -->

 

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

    <title>Sum the Elements of an Array</title>

 

      <script type = "text/javascript">

      <!--

 

      var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];

 

var total1 = 0, total2 = 0;

      // iterates through the elements of the array in order and adds

 

      // each element's value to total1

 

for ( var i = 0; i < theArray.length; i++ )

total1 += theArray[ i ];

document.writeln( "Total using subscripts: " + total1 );

      // iterates through the elements of the array using a for... in

 

      // statement to add each element's value to total2

 

for ( var element in theArray )

total2 += theArray[ element ];

      document.writeln( "<br />Total using for...in: " + total2 );

      // -->

 

      </script>

 

      </head><body></body>

 

</html>


Fig. 10.5 | Summing elements of an array.

word in (theArray in this case). When using forin, JavaScript automatically deter-mines the number of elements in the array. As the JavaScript interpreter iterates over theArray’s elements, variable element is assigned a value that can be used as a subscript for theArray. In the case of an Array, the value assigned is a subscript in the range from 0 up to, but not including, theArray.length. Each value is added to total2 to produce the sum of the elements in the array.

Using the Elements of an Array as Counters

 

In Chapter 9, we indicated that there is a more elegant way to implement the dice-rolling program in Fig. 9.5. The program rolled a single six-sided die 6000 times and used a switch statement to total the number of times each value was rolled. An array version of this script is shown in Fig. 10.6. The switch statement in Fig. 9.5 is replaced by line 24 of this program. This line uses the random face value as the subscript for the array fre-quency to determine which element to increment during each iteration of the loop. Be-cause the random number calculation in line 23 produces numbers from 1 to 6 (the values for a six-sided die), the frequency array must be large enough to allow subscript values of 1 to 6. The smallest number of elements required for an array to have these subscript values is seven elements (subscript values from 0 to 6). In this program, we ignore element 0 of array frequency and use only the elements that correspond to values on the sides of a die. Also, lines 32–34 of this program use a loop to generate the table that was written one line at a time in Fig. 9.5. Because we can loop through array frequency to help produce the output, we do not have to enumerate each XHTML table row as we did in Fig. 9.5.

 

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 10.6: RollDie.html -->

 

      <!-- Dice-rolling program using an array instead of a switch. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Roll a Six-Sided Die 6000 Times</title>

 

        <style type = "text/css">

 

        table { width: 15em }

              th   { text-align: left }

 

        </style>

 

        <script type = "text/javascript">

        <!--

 

        var face;

 

var frequency = [ , 0, 0, 0, 0, 0, 0 ]; // leave frequency[0]

        // summarize results

 

        for ( var roll = 1; roll <= 6000; ++roll )

{

face = Math.floor( 1 + Math.random() * 6 );

        ++frequency[ face ];

 

        } // end for

        document.writeln( "<table border = \"1\"><thead>" );

 

document.writeln( "<th>Face</th>" +

"<th>Frequency</th></thead><tbody>" );

        // generate entire table of frequencies for each face

 

for ( face = 1; face < frequency.length; ++face )

document.writeln( "<tr><td>" + face         + "</td><td>" +

frequency[ face ] + "</td></tr>"      );

        document.writeln( "</tbody></table>" );

        // -->

 

        </script>

 

        </head>

 

        <body>

 

        <p>Click Refresh (or Reload) to run the script again</p>

 

        </body>

 

</html>


Fig. 10.6 | Dice-rolling program using an array instead of a switch.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.