Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www.austin.cc.tx.us/baldwin/

JavaScript Programming, Arrays

 
Java/Web Programming, Lecture Notes # 2130, Revised 05/24/98.

Preface

The material was prepared as part of a new tutorial that I plan to publish on Web programming in general.  It is not part of the Java academic curriculum at ACC.

The purpose of this series of lessons is to teach you how to program in JavaScript.  The goal is to provide a programming tutorial that will be accessible to persons with no programming experience and will be equally useful to persons who already have programming experience using JavaScript or some other language.

 

Introduction

Up to this point, we have discussed such concepts as data types, literals, variables, expressions, operators, and flow of control.  There is one more fundamental programming concept that we need to address before we proceed into the world of object-oriented programming (OOP) and begin studying JavaScript objects.  We need to learn about arrays.
 

Arrays in General

The use of an array is a fundamental programming concept in virtually all programming languages, although the actual implementation differs greatly among languages.

In many languages, an array is a data structure capable of containing one or more variables all of the same type and having the same name but accessible through use of an ordinal numeric index (ordinal meaning first, second, third, etc.).  For example, the following schematic shows how several different instances of a variable named score might be stored in an array.
 
 
score[0] = 98
score[1] = 76
score[2] = 87
score[3] = 43
...
score[50] = 99
 
If you were writing a script to maintain the scores on a series of tests, and to do various calculations on those scores such as calculating the average, you would have at least two choices.

One choice, which isn't a very good one, would be to create a separate variable with a different name for every score.  Then when the time came to calculate the average, you would find yourself writing very long statements such as:
 
 
average = (firstScore + secondScore + thirdScore + 
      ... + lastScore)/numberOfScores
 
Obviously, if there were very many scores, this would very quickly become burdensome.

On the other hand, if you were to maintain the scores in an array, where the size of the array is equal to the number of scores (no empty elements in the array), you could calculate an average using code something like the following:
 
 
sum = 0;
for(cnt = 0; cnt < scores.length; cnt++)
  sum += scores[cnt];
average = sum/scores.length
 
A for loop is used here to extract the score in each element in the array and add it into an accumulator named sum.  Then the sum is divided by the number of elements in the array to calculate the average.

In the common jargon, accessing each element in an array in succession is known as traversing the array.

Most languages also support the concept of multi-dimensional arrays.  The earlier example illustrated a set of scores in a single-column format.  This might be viewed as the scores for one student only.

But, what if you need to deal with scores for more than one student?  Then you could visualize the columns as being side-by-side in such a way that they form a rectangular grid of array elements with each element containing a score value.

You could then visualize this as a grid consisting of rows and columns and assign all the scores for each individual student to the elements in either a row or a column.  It wouldn't matter which you chose as long as you were consistent in your thinking.

This kind of structure is often referred to as a two-dimensional array and the individual elements in the array are accessed using a pair of index values as illustrated in the following box.
 
 
score[row,column]
 
You could extend this to three dimensions in which case it could be visualized as a cube.  For example, in this case, you might let each row represent an individual student, the values in each column for that row represent an individual score, and each layer of rows and columns represent one year in school such as first grade, second grade, etc.

As a programmer, you can extend the array to four, five, or more dimensions.  However, at that point it becomes very difficult to form a mental picture of the array because our ability to form mental pictures is generally limited to the three dimensions of height, width, and depth.
 

Arrays in JavaScript

Some languages such as Pascal have an intrinsic array type that lets you declare variables of type array.  Many modern languages such as C++, Java and JavaScript don't have an array type.  Rather, they make it possible for you to instantiate special objects that have the capability to maintain and manipulate arrays.

JavaScript has a predefined object type named Array, and the use of that object provides a way to create an array.

This lesson will teach you how to use the predefined Array object.  It will illustrate what to do and how to do it but not necessarily why.  You will have to wait for our discussion on objects to learn that.

Why am I jumping ahead and discussing the Array object before I discuss the general topic of JavaScript objects?  Because this is something of a catch 22.  You need to know about arrays in order to understand some aspects of objects, and you need to know about objects to understand the Array object.
 

Using The Array Constructors

An Array object represents an array of elements as described in an earlier section. You can instantiate an Array object by invoking one of the available constructors with the new operator as shown below. Any one of these three statements would create a new array named myArray having certain characteristics that will be discussed in the following paragraphs.

For the time being, don't be too concerned about what I mean by a constructor.  You will learn what a constructor is later in the lessons on objects.
 
myArray = new Array(3);

myArray = new Array(23, 14, 12, 18);

myArray = new Array();
 
Prior to JavaScript 1.2, the first case would instantiate a new Array object named myArray with three undefined elements.
 
Important:  Things have changed.  With JavaScript 1.2, the use of the first constructor above instantiates a one-element array and initializes that element with a value of 3 instead of instantiating a three-element array of undefined elements.  This is clearly a code breaker.  You will want to be very careful about using existing scripts developed under earlier versions of JavaScript and treating them as Version 1.2 scripts. 

It isn't clear from the documentation how you would go about creating an array of a given length with JavaScript 1.2. Unless you are prepared to initialize your Array object when you instantiate it, you should probably use the third form of the constructor shown above that has an empty argument list.  This constructor instantiates an array with no elements.  You can then let your array grow as needed during execution of the program.  We will discuss the automatic growth of arrays in more detail later.

 
The second constructor shown above will instantiate a new Array object named myArray with four elements initialized to the values 23, 14, 12, and 18.

For the first constructor, (prior to V1.2) the length property of the Array object will return a value of 3 and for the second constructor, it will return a value of 4.

Element numbers or array index values in JavaScript begin with zero. Therefore, the maximum index value will always be one less than the length.  If you fail to take this into account, particularly when using loops to traverse the array, you can cause some really bad thing to happen (such as the array trying to grow to infinite size which has a number of undesirable consequences).

Once you have created the array using any one of the three constructors, you can modify the values stored in the elements as illustrated in the sample script that follows.

This script is designed to illustrate the instantiation and manipulation of Array objects using a JavaScript version prior to V1.2.  Version control is accomplished by omitting the version number from the following statement:

<SCRIPT LANGUAGE="JavaScript">

This script instantiates three arrays in succession using each of the three available constructors and then manipulates the data in the arrays.

The first array, named myFirstArray,  was instantiated using the constructor that provides for initializing the values in the the elements when the array object is instantiated.  Four values, separated by commas, were passed to the constructor as shown below.

myFirstArray = new Array(23, 14, 12, 18);

This resulted in an array with a length of four.  A for loop was used to traverse the array displaying each of the values, and as expected, they match the values passed to the constructor.

Then the value in the element at index number 2 was purposely modified using the following statement.

myFirstArray[2] = 3642.99999

All of the elements were displayed again, showing that the element was properly modified.

Following this, a second array object named mySecondArray was instantiated using the following version of the constructor.

mySecondArray = new Array(3);

Because this script was defined to be pre-V1.2, this resulted in a three-element array with all of the elements being undefined as was shown when the elements were later displayed.  As before, one of the elements was modified using the following statement

mySecondArray[2] = 3642.99999

and the elements were displayed again.  As expected, this particular element took on the new value and the other two elements were still undefined.

Finally, a third array object with the name myThirdArray was instantiated using the following constructor with an empty argument list.

myThirdArray = new Array();

This resulted in an array having a length of zero.  When an attempt was made to display the elements, there was nothing to display.

Then, as before, a value was assigned to the element at index 2 using the following statement

myThirdArray[2] = 3642.99999

and another attempt was made to display the contents of the elements.  The result is extremely important to your understanding of the use of arrays in JavaScript, and as such is reproduced below for convenient viewing.
 
Create myThirdArray without initial values
Array length = 0
Display myThirdArray without initial values

Modify a value in myThirdArray

Display myThirdArray with modified value
Element 0 = undefined
Element 1 = undefined
Element 2 = 3642.99999
 
This output illustrates the important capability of the JavaScript Array object to automatically increase its size as needed to accommodate an attempt to store data in an element that is outside the bounds of the current Array object.  Such an attempt will cause the new size of the array to be sufficiently large to contain the data value in the specified element.

This is what prompts me to say that with V1.2, unless you are prepared to initialize your array elements when you instantiate the Array object, you should use the constructor with the empty argument list and allow the array to automatically grow in size as needed to accommodate the needs of the script.

The sample script follows:
 
<!-- File Js00000290.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the instantiation and
manipulation of Array objects using a JavaScript version prior
to V1.2.

The output from running this script is:
This is a pre-V1.2 version of JavaScript
Create myFirstArray with initial values
Array length = 4
Display myFirstArray with initial values
Element 0 = 23
Element 1 = 14
Element 2 = 12
Element 3 = 18

Modify a value in myFirstArray

Display myFirstArray with modified value
Element 0 = 23
Element 1 = 14
Element 2 = 3642.99999
Element 3 = 18

Create mySecondArray without initial values
Array length = 3
Display mySecondArray without initial values
Element 0 = undefined
Element 1 = undefined
Element 2 = undefined

Modify a value in mySecondArray

Display mySecondArray with modified value
Element 0 = undefined
Element 1 = undefined
Element 2 = 3642.99999

Create myThirdArray without initial values
Array length = 0
Display myThirdArray without initial values

Modify a value in myThirdArray

Display myThirdArray with modified value
Element 0 = undefined
Element 1 = undefined
Element 2 = 3642.99999

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript">
      <!-- Hide script

      document.write("This is a pre-V1.2 version of JavaScript<BR>");
      document.write("Create myFirstArray with initial values<BR>");
      myFirstArray = new Array(23, 14, 12, 18);
      document.write(
                   "Array length = " + myFirstArray.length + "<BR>");
      document.write("Display myFirstArray with initial values<BR>");
      for(cnt = 0; cnt < myFirstArray.length ; cnt++)
        document.write(
             "Element " + cnt + "  = " + myFirstArray[cnt] + "<BR>");
      document.write("<BR>Modify a value in myFirstArray<BR>");
      myFirstArray[2] = 3642.99999
      document.write(
                 "<BR>Display myFirstArray with modified value<BR>");
      for(cnt = 0; cnt < myFirstArray.length ; cnt++)
        document.write(
             "Element " + cnt + "  = " + myFirstArray[cnt] + "<BR>");

      document.write(
              "<BR>Create mySecondArray without initial values<BR>");
      mySecondArray = new Array(3);
      document.write(
                  "Array length = " + mySecondArray.length + "<BR>");
      document.write(
                 "Display mySecondArray without initial values<BR>");
      for(cnt = 0; cnt < mySecondArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + mySecondArray[cnt] + "<BR>");
      document.write("<BR>Modify a value in mySecondArray<BR>");
      mySecondArray[2] = 3642.99999
      document.write(
                "<BR>Display mySecondArray with modified value<BR>");
      for(cnt = 0; cnt < mySecondArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + mySecondArray[cnt] + "<BR>");

      document.write(
               "<BR>Create myThirdArray without initial values<BR>");
      myThirdArray = new Array();
      document.write(
                   "Array length = " + myThirdArray.length + "<BR>");
      document.write(
                  "Display myThirdArray without initial values<BR>");
      for(cnt = 0; cnt < myThirdArray.length ; cnt++)
        document.write(
             "Element " + cnt + "  = " + myThirdArray[cnt] + "<BR>");
      document.write("<BR>Modify a value in myThirdArray<BR>");
      myThirdArray[2] = 3642.99999
      document.write(
                 "<BR>Display myThirdArray with modified value<BR>");
      for(cnt = 0; cnt < myThirdArray.length ; cnt++)
        document.write(
             "Element " + cnt + "  = " + myThirdArray[cnt] + "<BR>");

      // End hiding  -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <P> Done.
  </BODY>
</HTML>
 
The next sample script is identical to the middle portion of the previous one except that this script is defined to be a V1.2 script by using the following tag.

<SCRIPT LANGUAGE="JavaScript1.2">

The behavior of the constructors for the first and third objects in the previous script did not change with the advent of JavaScript V1.2.  Therefore, that code was excluded from this sample script.

As in the previous script, an Array object was instantiated using the following constructor whose behavior has changed in V1.2.

mySecondArray = new Array(3);

Whereas the behavior of this constructor was previously to create a three-element array with undefined elements, under V1.2, it created a one-element array whose value was initialized to 3.  Again, this is a code-breaking change and you will need to be very careful about using existing scripts developed under earlier versions of JavaScript.

Following this, data was added to the array at index 2.  As you can see in the output below, this caused the length of the array to automatically increase to 3, leaving element 1 as undefined.
 
<!-- File Js00000300.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the instantiation and
manipulation of Array objects using JavaScript version 1.2
and the constructor whose behavior was modified in V1.2.

The output from running this script is:
This is a V1.2 version of JavaScript

Create mySecondArray without initial values
Array length = 1
Display mySecondArray without initial values
Element 0 = 3

Modify a value in mySecondArray

Display mySecondArray with modified value
Element 0 = 3
Element 1 = undefined
Element 2 = 3642.99999

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script

      document.write("This is a V1.2 version of JavaScript<BR>");

      document.write(
              "<BR>Create mySecondArray without initial values<BR>");
      mySecondArray = new Array(3);
      document.write(
                  "Array length = " + mySecondArray.length + "<BR>");
      document.write(
                 "Display mySecondArray without initial values<BR>");
      for(cnt = 0; cnt < mySecondArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + mySecondArray[cnt] + "<BR>");
      document.write("<BR>Modify a value in mySecondArray<BR>");
      mySecondArray[2] = 3642.99999
      document.write(
                "<BR>Display mySecondArray with modified value<BR>");
      for(cnt = 0; cnt < mySecondArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + mySecondArray[cnt] + "<BR>");

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>

    <P> Done.
  </BODY>
</HTML>
 
As shown earlier, an array's length increases if you assign a value to an element number that is outside the current bounds of the array.  This can leave elements internal to the array which have not been assigned a value.  These elements are shown as undefined.

An array with no undefined elements is known as a dense array.  You can construct a dense array of two or more elements starting with index 0 if you define initial values for all elements.  The four-element array that we created earlier by initializing all four elements was a dense array. There are, of course, other ways to create a dense array as well.
 

Arrays with Mixed Element Types

Unlike some other languages, an array in JavaScript is not confined to contain only elements of the same type.  In fact, a JavaScript array can have elements that are a mixture of numeric, string, or boolean types, or even other objects.  Those other objects can themselves be Array objects, and that is one way to create multidimensional arrays in JavaScript.  We will see how to do this later.

In the meantime, the following script illustrates the instantiation and initialization of an Array object with numeric, string, and boolean elements.  After the array is instantiated and displayed, one of the boolean elements is replaced by a numeric element and the array is displayed again.  This illustrates that it is not only allowable to initialize an array with elements of different types, it is also allowable to change the type of an element in an existing array.
 
<!-- File Js00000310.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the instantiation and
manipulation of Array objects with mixed element types.

The output from running this script is:
Create myArray with initial values
Array length = 4
Display myArray
Element 0 = 3.14159
Element 1 = Pi
Element 2 = true
Element 3 = false

Modify a value in myArray

Display myArray with modified value
Element 0 = 3.14159
Element 1 = Pi
Element 2 = 3642.99999
Element 3 = false

Done.  
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script

      document.write(
              "<BR>Create myArray with initial values<BR>");
      myArray = new Array(3.14159,"Pi",true,false);
      document.write(
                  "Array length = " + myArray.length + "<BR>");
      document.write(
                 "Display myArray<BR>");
      for(cnt = 0; cnt < myArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + myArray[cnt] + "<BR>");
      document.write("<BR>Modify a value in myArray<BR>");
      myArray[2] = 3642.99999
      document.write(
                "<BR>Display myArray with modified value<BR>");
      for(cnt = 0; cnt < myArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + myArray[cnt] + "<BR>");

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <P> Done.
  </BODY>
</HTML>
.



Associative Arrays

The power of the JavaScript Array object goes far beyond the simple numerically indexed array concepts described earlier in this lesson.  Each element in the array can be a numeric, string, or boolean value, or another object.  As you are already aware, you can access those elements using the ordinal numeric index.

For the case where the element is a string, boolean, or non-integer numeric, you can associate another variable or object with that element and access that new variable or object using the name of the original array and the value stored in the element.  This opens up the possibility for lots of different kinds of sophisticated data structures based on the storage and retrieval of key-value pairs.

This capability is illustrated in the following sample script.  Initially, the script instantiated an Array object named myArray and populated four elements with a boolean, a string, a float, and another string.  The values of these four elements were

Let's refer to these as the keys so we will have a convenient way to discuss them.

Then the script displayed the keys in each of the four elements using the ordinal index values in a for loop.

Next, the script associated a value with each of the four keys using assignment statements such as the following:

In this case, the keys were of mixed types and the values associated with the keys were also of mixed types.

Note in particular that in each of these cases, an array element was accessed using the key stored in the element.  Then those same keys were used to access the array and display the values that were retrieved.  The result was to display the values stored there as would be expected.  This produced an output of key-value pairs that looks like:

This demonstrates the ability to store a key in an array element, store a value by associating it with that key, and then retrieving it using the key as the index. As mentioned earlier, this is a very powerful capability.

After this, the script demonstrated that it is possible to add new key-value pairs to the array and successfully use the key to retrieve the value.

Finally, the program experimented with duplicate keys.  The result was that if a new key and  associated value is added to an array, and this new key is the same as one already stored in the array, even though the first key does not cease to occupy an element in the array, an attempt to access the value using the key retrieves the most recently stored value associated with the duplicated key.  A practical program making use of this key-value capability should perform tests to avoid having duplicate keys.
 
<!-- File Js00000320.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the use of the Array object
to create and manipulate associative arrays.

The output from running this script is:
Create myArray with initial non-integer values
Array length = 4
Display myArray
Element 0 = true
Element 1 = Dick
Element 2 = 3.62
Element 3 = Sue

Associate each element value with another value
Display the value associated with each element value the hard way
true = 3.14159
Dick = true
3.62 = Tommy
Sue = false

Add another string element to the array
Associate the new string element with a value
Display them all again including the new one the automated way
true = 3.14159
Dick = true
3.62 = Tommy
Sue = false
Mary = Mary's data

Add a duplicate value to the array and try it again
to determine the behavior for duplicate keys.
Associate the new string element with a value
Display them all again including the new one
true = 3.14159
Dick = true
3.62 = Tommy
Sue = false
Mary = 1234567
Mary = 1234567

Done.   
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script

      document.write(
           "<BR>Create myArray with initial non-integer values<BR>");
      myArray = new Array(true, "Dick", 3.62, "Sue");
      document.write(
                  "Array length = " + myArray.length + "<BR>");
      document.write(
                 "Display myArray<BR>");
      for(cnt = 0; cnt < myArray.length ; cnt++)
        document.write(
            "Element " + cnt + "  = " + myArray[cnt] + "<BR>");

      document.write(
          "<BR>Associate each element value with another value<BR>");
      myArray[true] = 3.14159;
      myArray["Dick"] = true;
      myArray[3.62] = "Tommy";
      myArray["Sue"] = false;

      document.write("Display the value associated with each "
                                 + "element value the hard way<BR>");
      document.write("true = " + myArray[true] + "<BR>");
      document.write("Dick = " + myArray["Dick"] + "<BR>");
      document.write("3.62 = " + myArray[3.62] + "<BR>");
      document.write("Sue = " + myArray["Sue"] + "<BR>");

      document.write(
                  "<BR>Add another string element to the array<BR>");
      myArray[myArray.length] = "Mary";
      document.write(
                "Associate the new string element with a value<BR>");
      myArray["Mary"]="Mary's data";
      document.write("Display them all again including the new one "
                                          + "the automated way<BR>");
      for(cnt = 0; cnt < myArray.length; cnt++){
        document.write(
              myArray[cnt] + " = " + myArray[myArray[cnt]] + "<BR>");
      }//end for loop

      document.write("<BR>Add a duplicate value to the array and "
                                               + "try it again<BR>");
      document.write(
                "to determine the behavior for duplicate keys.<BR>");
      myArray[myArray.length] = "Mary";
      document.write(
                "Associate the new string element with a value<BR>");
      myArray["Mary"]="1234567";
      document.write(
                 "Display them all again including the new one<BR>");
      for(cnt = 0; cnt < myArray.length; cnt++){
        document.write(
              myArray[cnt] + " = " + myArray[myArray[cnt]] + "<BR>");
      }//end for loop

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <P> Done.
  </BODY>
</HTML>
.


Regular Expressions and the Array Object

The Array object provides special capabilities for the processing of regular expressions.  However, we will defer the discussion of that topic until we discuss regular expressions in their own right.
 

Properties

The following table summarizes the properties of the Array object.  Since we haven't discussed object properties yet, and I plan to defer that discussion until the general discussion on objects, about all that I can say at this time is that the length property which we used extensively in the above sample script can be used to determine the number of elements in the array. As far as the other properties are concerned, simply remember where to find this table once you have the background to understand the meaning of the descriptions.
 
Property Description
index For an array created by a regular expression match, the zero-based index of the match in the string.
input For an array created by a regular expression match, reflects the original string against which the regular expression was matched.
length Reflects the number of elements in an array
prototype Allows the addition of properties to an Array object.
.

Methods

Very briefly, methods are functions that are uniquely associated with objects.  This is something else that we will learn when we discuss objects.  You can invoke a method on a specific object to get the behavior provided by the method on that object.

The following table summarizes the methods that can be invoked on an object of type Array.  For the most part, you should be able to figure out what impact the invocation of one of these methods will have on the object on the basis of the method name and brief description.

For example, if we were to invoke the sort method on an Array object, that would cause the elements in the array to be sorted.

I'm not going to get into the behavior of these methods in detail at this time, but I hope to have the time to come back and discuss them in detail in a subsequent lesson.
 
 
 
Method Description 
concat Joins two arrays and returns a new array.
join Joins all elements of an array into a string.
pop Removes the last element from an array and returns that element.
push Adds one or more elements to the end of an array and returns that last element added.
reverse Transposes the elements of an array: the first array element becomes the last and the last becomes the first.
shift Removes the first element from an array and returns that element
slice Extracts a section of an array and returns a new array.
splice Adds and/or removes elements from an array.
sort Sorts the elements of an array.
toString Returns a string representing the specified object.
unshift Adds one or more elements to the front of an array and returns the new length of the array.
.

More Sample Scripts

I'm going to wrap up this lesson with three more sample scripts.  The first one shown below illustrates the use of the sort() method on an Array object.  This script creates a four-element array and populates it with four strings.  The contents of the array are displayed.

The script then invokes the sort() method on the array object and displays the contents again.  As you can see from the output shown below, the strings are sorted into alphabetic order.
 
<!-- File Js00000330.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the use of the sort method on
an Array object.

The output from running this script is:
Create myArray with initial string values
Display myArray
Element 0 = Tom
Element 1 = Dick
Element 2 = Harry
Element 3 = Sue

Sort and display the array
Element 0 = Dick
Element 1 = Harry
Element 2 = Sue
Element 3 = Tom

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script

      document.write(
                "<BR>Create myArray with initial string values<BR>");
      myArray = new Array("Tom", "Dick", "Harry", "Sue");
      document.write("Display myArray<BR>");
      for(cnt = 0; cnt < myArray.length ; cnt++)
        document.write(
                  "Element " + cnt + "  = " + myArray[cnt] + "<BR>");

      document.write("<BR>Sort and display the array<BR>");
      myArray.sort();
      for(cnt = 0; cnt < myArray.length ; cnt++)
        document.write(
                  "Element " + cnt + "  = " + myArray[cnt] + "<BR>");

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <P> Done.
  </BODY>
</HTML>
 

The next sample script creates and displays a two-dimensional array with four rows and five columns.  This is accomplished by creating a four-element array that represents the rows and populating each element in that array with another array containing five elements.

Each element in each five-element array is populated with a string containing information about the row number and the column number.

Then the contents of the four-element array are displayed producing the rectangular grid display shown below.
 
<!-- File Js00000340.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the use of the Array object
to create multi-dimensional arrays.

The output from running this script is:
Create and populate a 4x5 array
Display the array
Row 0:[0,0][0,1][0,2][0,3][0,4]
Row 1:[1,0][1,1][1,2][1,3][1,4]
Row 2:[2,0][2,1][2,2][2,3][2,4]
Row 3:[3,0][3,1][3,2][3,3][3,4]

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script
      noRows = 4, noCols = 5;
      document.write("Create and populate a 4x5 array<BR>");
      myArray = new Array();
      for (rowCnt=0; rowCnt < noRows; rowCnt++) {
        myArray[rowCnt] = new Array();
        for (colCnt=0; colCnt < noCols; colCnt++) {
          myArray[rowCnt][colCnt] = "[" + rowCnt + "," + colCnt + "]";
        }//end for loop on colCnt
      }//end for loop on rowCnt

      document.write("Display the array<BR>");
      for (rowCnt=0; rowCnt < noRows; rowCnt++) {
        str = "Row " + rowCnt + ":";
        for (colCnt=0; colCnt < noCols; colCnt++) {
          str += myArray[rowCnt][colCnt]
        }//end for loop
        document.write(str,"<BR>")
      }//end for loop

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <P> Done.
  </BODY>
</HTML>
 
Note that with JavaScript it is not necessary that every row have the same number of columns as is the case with some programming languages.  This is illustrated in the following script that creates, populates, and displays a triangular array.  This effect was achieved by causing the limit in the conditional clause of the for loop that deals with columns to be different for each row.
 
<!-- File Js00000350.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the fact that multi-dimensional
arrays in JavaScript don't have to be rectangular.

The output from running this script is:
Create and populate a triangular array
Display the array
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2]
Row 2:[2,0][2,1]
Row 3:[3,0]

Done.  
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script
      noRows = 4, noCols = 4;
      document.write("Create and populate a triangular array<BR>");
      myArray = new Array();
      for (rowCnt=0; rowCnt < noRows; rowCnt++) {
        myArray[rowCnt] = new Array();
        for (colCnt=0; colCnt < (noCols-rowCnt); colCnt++) {
          myArray[rowCnt][colCnt] = "[" + rowCnt + "," + colCnt + "]";
        }//end for loop on colCnt
      }//end for loop on rowCnt

      document.write("Display the array<BR>");
      for (rowCnt=0; rowCnt < noRows; rowCnt++) {
        str = "Row " + rowCnt + ":";
        for (colCnt=0; colCnt < (noCols-rowCnt); colCnt++) {
          str += myArray[rowCnt][colCnt]
        }//end for loop
        document.write(str,"<BR>")
      }//end for loop

      // End hiding  -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <P> Done.
  </BODY>
</HTML>
 
-end-