Team LiB
Previous Section Next Section

Chapter 3: Arrays and Strings

Arrays and strings are two of the most commonly used objects in the JavaScript language. Arrays are used to hold large amounts of data of the same type logically in memory so that each element can be accessed directly from the array name and index. Strings are collections of characters that can be manipulated with special built-in functions. You have already seen strings in the code examples in previous chapters. Any term surrounded by either single or double quotes is considered a string literal and is used to create a string object.

JavaScript Arrays

What would you do if you had 100 names you wanted to keep track of throughout the length of your program? One solution would be to create a separate variable for each name. Having done so, if you wanted to display each name on your Web page, you would have to write a separate output statement for each variable. Not only would this process be lengthy and inefficient, it would also make the size of your Web page much larger than it needed to be. A better solution would be to keep track of all the names in an array. Then, when you wanted to output them, you could just loop through the array and use the same output statement to display each one.

Single and Multi-Dimensional Arrays

The most commonly used type of array is a single-dimension array that holds a list of numbers or strings that are related in some way. For example, you might use an array to store the ISBN numbers of books your Web page visitor would like to check out of a library. Similarly, you might want to keep track of the title of each book so that you could display the list later on. Both would be valid uses for an array. The syntax for declaring an array is as follows:

var <identifier> = new Array( <size> );
  or
var <identifier> = new Array( <element>, <element>, ... );

The first way to declare an array is with only the size as an operand. This will create an array of the desired size, with empty elements. The second way of declaring an array is to provide a comma-separated list of elements that you would like to include in the array. The size of the array will depend on the number of elements you provide. Here is an example of declaring, filling, and outputting an array:

<html>

  <head>
    <title>
      JavaScript Professional Projects-Arrays
    </title>

    <script language="JavaScript">
    <!--
      var arraySize = 100;
      var theArray = new Array( arraySize );
      for( i = 0 ; i < arraySize ; i++ )
      {
        theArray[i] = parseInt( Math.random() * 100 );
      }
      // -->
     </script>

   </head>

   <body>

     <center>
       <font size=6>JavaScript Professional Projects</font><br>
       <font size=4>Chapter 3: Arrays</font>
     </center>

     <br><br>

     <p>
       <table>
         <script language="JavaScript">
         <!--
           for( i = 0 ; i < arraySize ; i++ )
           {
             if( i % 10 == 0 ) document.write( "<tr>" );
             document.write( "<td>" );
             document.write( theArray[i] );
             document.write( "</td>" );
             if( i % 10 == 9 ) document.write( "</tr>" );
           }
         // -->
         </script>
       <table>
     </p>

  </body>

</html>

This example creates a single-dimension array with size arraySize, which is declared as 100. The array is then filled with randomly generated integer numbers from 0 to 99. This way, in the body of the Web page, each element of the array is displayed in a 10 10 table. This example demonstrates one important point: It is always a good idea to keep a variable that holds the desired size of the array. This will make iterating through the array easier because you already know how large the array is. This technique will also make updating your code easier. If, in the example just given, the integer literal 100 had been used to declare the array, then you might be tempted to use the literal 100 while looping through the array. This would cause a problem later on if you decided to change the size of the array. Not only would you have to change the literal where you declared the array, but you would also have to find every other place where you used 100 as the array length and change that, too. By declaring a variable to keep track of the array length, you need only change the value of it in that one place in order for it to take effect throughout the page.

Unfortunately, single-dimension arrays do no always provide enough functionality for every problem you will have. If you decided to keep track of not only the ISBN number, but also the title, author, and publisher of books your Web page visitor wanted to check out of the library, you could do one of two things. You could create four parallel arrays—one to hold the ISBN, a second to hold the title, a third to hold the author's name, and a fourth to hold the name of the book's publisher. This approach works, but may lead to confusion later on. A better way to keep track of all that information would be to use a two-dimension array.

<html>

  <head>
    <title>
      JavaScript Professional Projects-Multi-Dimensional Arrays
    </title>
    
     <script language="JavaScript">
      <!--
        var numBooks = 5;
        var bookInfo = new Array( numBooks );
       
        bookInfo[0] = new Array( 4 );
        bookInfo[0][0] = "0-201-10088-6";
        bookInfo[0][1] = "Compilers Principles, Techniques, and Tools";
        bookInfo[0][2] = "Alfred V. Aho etc." 
        bookInfo[0][3] = "Addison-Wesley Publishing Company"; 
        
        bookInfo[1] = new Array( 4 );
        bookInfo[1][0] = "0-201-89685-0";
        bookInfo[1][1] = "The Art of Computer Programming Vol.3";
        bookInfo[1][2] = "Donald E. Knuth";
        bookInfo[1][3] = "Addison-Wesley";
        
        bookInfo[2] = new Array( 4 );
        bookInfo[2][0] = "0-13-899394-7";
        bookInfo[2][1] = "Java-How to Program";
        bookInfo[2][2] = "Deitel & Deitel";
        bookInfo[2][3] = "Prentice Hall";
        
        bookInfo[3] = new Array( 4 );
        bookInfo[3][0] = "0-7645-4003-3";
        bookInfo[3][1] = "HTML & Web Publishing Secrets";
        bookInfo[3][2] = "Jim Heid";
        bookInfo[3][3] = "IDG Books Worldwide, Inc.";
 
        bookInfo[4] = new Array( 4 );
        bookInfo[4][0] = "0-13-091013-9";
        bookInfo[4][1] = "Assembly Language for Intel-Based Computers";
        bookInfo[4][2] = "Kip R. Irvine";
        bookInfo[4][3] = "Prentice Hall";
      // -->
      </script>
    

    </head>
    

    <body>
    
      <center>
        <font size=6>JavaScript Professional Projects</font><br>
        <font size=4>Chapter 3: Multi-Dimensional Arrays </font>
      </center>
      
      <br><br>
      

      <p>
        <table border="1" cellpadding="2" cellspacing="1">
          <tr>
            <td><b>ISBN</b></td>
            <td><b>Title</b></td>
            <td><b>Author</b></td>
            <td><b>Publisher</b></td>
         <script language="JavaScript">
         <!--
           for( i = 0 ; i < numBooks ; i++ )
           {
             document.write( "<tr>" );
          
             document.write( "<td>" + bookInfo[i][0] + "</td>" );
             document.write( "<td>" + bookInfo[i][1] + "</td>" );
             document.write( "<td>" + bookInfo[i][2] + "</td>" );
             document.write( "<td>" + bookInfo[i][3] + "</td>" );
          

             document.write( "</tr>" );
           }
         // -->
           </script>
      <table>
     </p>

  </body>

</html>

This example essentially uses an array of arrays to hold all of the information for each book. The first array declaration creates the first dimension of the multi-dimension array. Afterwards, each element in the first array—representing each book—is initialized as another array of size 4. Each element in the second-dimension array will hold the information for the book. The only limit to the number of dimensions an array can have is the amount of memory the program is running on.

Elements in an Array

Easy access to any element in an array is one of the biggest benefits of using arrays. You can get or set the value of any element in an array simply by specifying its index. For example, an array declared as

var theArray = new Array("January","February","March","April");

has a length of 4. The string "January" has an index of 0, "February" has an index of 1, "March" has an index of 2, and "April" has an index of 3. It is important to remember that arrays in JavaScript have a zero-based indexing system. In the previous array, referencing the element at index 4 will cause an error in your program. The largest index of any array will be its length – 1. To reference the elements of an array in your program, you simply put the index within square braces after the array name:

document.write( theArray[0] + " is the first month" +
                  "of the year.<br>" );

document.write( theArray[1] + " is the shortest month" +
                  "of the year.<br>" );

document.write( "Spring begins in " + theArray[2] + ".<br>" );

document.write( theArray[3] + " showers bring" + 
                  "May flowers.<br>" );

Using elements in a multi-dimensional array is just as easy. Instead of a single set of square braces, you will need to use the same number as there are dimensions in the array. If an array is declared as

       var bookInfo = new Array( 1 );
       bookInfo[0] = new Array( 4 );

then referencing the elements in the second dimension could be done like this:

       bookInfo[0][0] = "0-201-10088-6";
       bookInfo[0][1] = "Compilers Principles, Techniques, and Tools";
       bookInfo[0][2] = "Alfred V. Aho etc.";
       bookInfo[0][3] = "Addison-Wesley Publishing Company";

The first set of square braces refers to the elements in the first dimension of this two-dimensional array, and the second set refers to elements in the second dimension.

Most of the time, you will be referencing the elements of an array within some type of loop. for loops are ideal for iterating through arrays. The basic structure of a for loop that iterates through a single-dimension array would be as follows:

var theArray = new Array( <some size> );
for( index = 0 ; index < theArray.length ; index++ )
{
  <statements referencing theArray[index]>
}

The for loop is not the only way to loop through all of an array's elements. The for-in loop structure was designed specifically to iterate through an array of elements. The previous example could just as easily be written as

var theArray = new Array( <some size> );
for( index in theArray )
{
   <statements referencing theArray[index]>
}

It is up to you, as the programmer, to decide which loop structure suits your needs.

Iterating through multi-dimensional arrays usually requires nested loops like this:

var theArray = new Array( <some size> );

// Create the second dimension
for( index in theArray )
{

}

// Iterate through both dimensions of the array
for( i = 0 ; i < theArray.length ; i++ )
{
  for( i = 0 ; i < theArray[i].length ; i++ )
  {
    <statements referencing theArray[i][j]>
  }
}

This example will loop through each element in a two-dimensional array. The last nested for loops could just as easily be written with nested for-in loops, like this:

// Iterate through both dimensions of the array
for( i in theArray )
{
  for( j in theArray[i] )
  {
    <statements referencing theArray[index]>
  }
}

Again, both methods accomplish the same result.

Array-Specific Properties and Methods

As you'll recall, I stated back in Chapter 1 that arrays were nothing more than specialized objects. Like all objects, an array has many properties, and methods are built into the Array object to make working with it much easier.

Array Properties

The following subsections contain descriptions of the Array object's properties.

length

The length property is the total number of element spaces allocated in the array. If the array constructor specified a size, this property reflects that amount, even if data is not stored in each element.

prototype

The prototype property is a static property of the Array object. Use the prototype property to assign new properties and methods to the Array object in the current document.

To add an additional method to the Array object, all you'd need to do is write the corresponding function:

function print()
{
  for( index = 0 ; index < this.length ; index++ )
  {
    document.write( this[index] + "<br>" );
  }
}

Then simply add it to the prototype property of the static Array object:

Array.prototype.print = print;

Then, whenever a new instance of the Array object is created, a new method, print, will be available to it:

var theDays = new Array( "Sun", 'Mon", "Tues", "Wed",
"Thurs", "Fri", "Sat" );

theDays.print();

When the print method is called, each element in the array will be printed on its own line in the Web page.

Array Methods

There are some very useful methods that are part of the Array object definition. The following subsections name and describe them.

concat (array2)

The concat (array2) method combines the current array with the array specified as the parameter.

Following is an example of using the concat() method:

var myArray3 = myArray1.concat( myArray2 );

The array instance myArray3 will now contain all the elements in myArray1 followed by myArray2. Neither of the original arrays is altered in any way.

join (delimiter)

The join(delimiter) method returns a string containing each element in the array separated by delimiter.

Following is an example of the join() method:

var myArray = new Array( "Yesterday", "Today", "Tomorrow" );
document.write( myArray.join( "," ) + "<br>" );

The output of this code segment would be:

Yesterday,Today,Tomorrow.

pop()

The pop() method removes the last elements in the array and returns its value; the size of the array is decreased by one.

Following is an example of the pop() method:

var myArray = new Array( "Yesterday", "Today", "Tomorrow" );

for( i = 0 ; i < myArray.length ; i++ )
{
document.write( myArray[i] + ", " );
}
myArray.pop();

for( i = 0 ; i < myArray.length ; i++ )
{
document.write( myArray[i] + ", " );
}

The output from this code segment would be the original array,

Yesterday, Today, Tomorrow

followed by the altered array,

Yesterday, Today

The length of the original array is now equal to two.

push (value)

The push() method appends values to the end of the array; the size of the array is increased by one.

Following is an example of the push() method:

var myArray = new Array( "Yesterday", "Today" );

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

myArray.push( "Tomorrow" );

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );

}

The output from this code segment would be the original array,

Yesterday, Today

followed by the altered array,

Yesterday, Today, Tomorrow

The length of the original array is now equal to three.

reverse()

The reverse() method reverses the order of the elements in the array and returns a new array with the reversed elements. The order of the original array is changed after this method is executed.

Following is an example of the reverse() method:

var myArray = new Array( "Yesterday", "Today", "Tomorrow" );

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

myArray.reverse();

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

The output from this code segment would be the original array,

Yesterday, Today, Tomorrow

followed by the altered array,

Tomorrow, Today, Yesterday

The length of the original array does not change.

shift()

The shift() method removes the first element in the array and returns its value; the size of the array is decreased by one.

Following is an example of the shift() method:

var myArray = new Array( "Yesterday", "Today", "Tomorrow" );

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}
myArray.shift();

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

The output from this code segment would be the original array,

Yesterday, Today, Tomorrow

followed by the altered array,

Today, Tomorrow

The length of the original array is now equal to two.

slice(startIndex, endIndex)

The slice(startIndex, endIndex) method returns a subset of the array starting from startIndex and ending with endIndex. If endIndex is omitted, the last element of the array is taken to be endIndex. The total number of elements in the subset array is equal to endIndex - startIndex.

Following is an example of the slice() method:

var theDays = new Array( "Sun", "Mon", "Tues", "Wed",
                             "Thurs", "Fri", "Sat" );

var days1 = theDays.slice( 2, 6 );

var days2 = theDays.slice( 4 );

At the end of execution, the array days1 will contain 4 elements of the original array:

"Tues", "Wed", "Thurs" and "Fri"

The array days2 will contain three elements of the original array:

"Thurs", "Fri" and "Sat"

sort (compare Function)

The sort (compare Function) method sorts the values of the array by the ASCII value of string by default or by a compareFunction function of your own design. The comparison function should take two parameters and return an integer value. The comparison function is optional. The sort function not only rearranges the elements in the array, but also returns a copy of the array.

Following is an example of the sort() method:

var theDays = new Array( "Sun", "Mon", "Tues", "Wed",
                             "Thurs", "Fri", "Sat" );
theDays.sort();

After execution, the elements in the theDays array will be in sorted order:

"Fri", "Mon", "Sat", "Sun", "Tues", "Wed"

If you want to sort the elements of an array in a way other than the default, you can create your own compare function, like this:

function compare( a, b )
{
  return( a-b );
}

This compare function would be ideal for sorting numerical data. The return value is interpreted by the arrays sort method, as shown in Table 3.2.

Table 3.2: Compare Function Return Value

Return Value

Meaning


Less than zero

The second value should appear before the first.

Equal to zero

Both values are equal.

Greater than zero

The first value should appear before the second.

To sort an array with this compare function, you could do the following:

var numbers = new Array( 8888, 3561, 0, 4133, 5555, 62, 1 );

numbers.sort( compare );

document.write( numbers.join( "<br>" ) );
The output from this code segment would be
       0
       1
       62
       3561
       4133
       5555
       8888
unshift(value)

The unshift(value) method inserts value at the beginning of the array; the size of the array is increased by one.

Following is an example of using the unshift() method:

var myArray = new Array( "Today", "Tomorrow" );
for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

myArray.unshift( "Yesterday" );

for( i = 0 ; i < myArray.length ; i++ )
{
  document.write( myArray[i] + ", " );
}

The output from this code segment would be the original array,

Today, Tomorrow

followed by the altered array,

Yesterday, Today, Tomorrow

The length of the original array is now equal to three.

Using Arrays

The built-in methods of the Array object lend themselves greatly to using arrays as dynamic data structures. Together, the Array object's push(), pop(), shift(), and unshift() methods can be used to simulate many common dynamic data structures, such as linked lists (the most commonly used data structure in computer science), stacks, and queues. To use an array as a stack, use the push() method to insert elements into the array and the pop() method to remove elements from the array. To use an array as a queue, use only the push() and shift() methods to insert and remove elements from the array. A linked list uses any of the insert/remove methods that are part of the array methods and still allows the use of array indexing.

Some functionality needed from the default array object to make array instances easily usable as a linked list is missing—mainly the insertAt() and removeAt() methods. Thanks to the prototype property, this problem is easily solved. Both functions are simple enough to design:

function insertAt( index, value )
{
  var part1 = this.slice( 0, index );
  var part2 = this.slice( index );
  part1.push( value );
  return( part1.concat( part2 ) );
}
Array.prototype.insertAt = insertAt;

This method will allow you to insert an element anywhere within an array bounds.

The removeAt() function is equally simple:

function removeAt( index )
{
  var part1 = this.slice( 0, index );
  var part2 = this.slice( index );
  part1.pop();
  return( part1.concat( part2 ) );
}
Array.prototype.removeAt = removeAt;

Both of these new methods will allow you to make an array a fully functional linked list. Here is a brief example of these two methods in use:

<html>

  <head>
    <title>
      JavaScript Professional Projects Using Arrays
    </title>

    <script language="JavaScript">
    <!--
      function insertAt( index, value )
      {
        var part1 = this.slice( 0, index );
        var part2 = this.slice( index );
        part1.push( value );
        return( part1.concat( part2 ) );
      }
      Array.prototype.insertAt = insertAt;

      function removeAt( index )
      {
        var part1 = this.slice( 0, index );
        var part2 = this.slice( index );
        part1.pop();
        return( part1.concat( part2 ) );
      }
      Array.prototype.removeAt = removeAt;
    // -->
    </script>

    </head>

    <body>
      <center>
        <font size=6>JavaScript Professional Projects</font><br>
        <font size=4>Chapter 3: Using Arrays</font>
      </center>
      <br><br>
      <p>
        <b>Before:</b><br>
        <script language="JavaScript">
        <!--
          var numbers = new Array( 8888, 3561, 0, 4133, 5555, 62, 1 );
          document.write( numbers.join( "<br>" ) );
        // -->
        </script>
        <br><br>
        <b>After:</b><br>
        <script language="JavaScript">
        <!--
          numbers = numbers.removeAt( 5 );
          numbers = numbers.insertAt( 2, 666 );
          document.write( numbers.join( "<br>" ) );
        // -->
        </script>
      </p>
   </body>
</html>

The ability to use linked lists in your programs will open many doors for organizing, sorting, and manipulating data. Using dynamic data structures, such as linked lists, will decrease the amount of memory your program requires to run, but will also increase its complexity.


Team LiB
Previous Section Next Section