MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Answers

Discussions of Exercise 1

The answers and discussion of the questions are as follows:

An element of an array is referred to with the array name and the index in square brackets. The first element is that indexed with 0, so it is weekDays[0] and so on:

  • The first element is: weekDays[0]

  • The last element: weekDays[6]

  • The 4th element: weekDays[4]

  • The value of weekDays[0] is "Monday" (we can see this from the figure), and so on.

  • The value of the first element: "Monday"

  • The value of the 4th element: "Friday"

  • The element of the array is referring to the part of weekDays that contains the value, i.e. weekDays[0] or weekDays[6] and so on.

  • The element containing String "Monday": weekDays[2]

  • The element containing String "Saturday": weekDays[5]

The index of the array element is referring to the number of the weekDays element containing the given value; since "Monday" is stored in weekDays[2], the index of this element is 2:

  • The index of the element containing String "Monday": 2

  • The index of the element containing String "Saturday": 5

Discussions of Exercise 2

After execution of the first two lines, memory looks as follows:

Since thing2 refers to the same array values as myArray, after the three lines:

thing2[1] = 27;
thing2[2] = 19;
thing2[3] = 77;  
      

memory will have been changed as follows:

Therefore the value of myArray[2] is now 19.

Discussions of Activity 1

The following code will fulfil the requirements:

      <html> <script> <!--

        var ages = new Array( 21, 14, 33, 66, 11 );
        document.write( "<p><b>ages[0] </b>" + ages[0]);
        document.write( "<p><b>ages[1] </b>" + ages[1]);
        document.write( "<p><b>ages[3] </b>" + ages[3]);

      // --> </script> </html>
      

This first line:

        var ages = new Array( 21, 14, 33, 66, 11 );
      

creates an array, and initialises it with the 5 values. This could have also been achieved as follows:

        var ages = new Array( 5 );

        ages[0] = 21;
        ages[1] = 14;
        ages[2] = 33;
        ages[3] = 66;
        ages[4] = 11;
      

The document.write( ... ) lines display the values of each specified array element.

Discussions of Activity 2

To create the primes array we can write the following:

        var primes = new Array( 6 );
      

To put the values into the array we can write the following:

        primes[0] = 1;
        primes[1] = 2;
        primes[2] = 3;
        primes[3] = 5;
        primes[4] = 7;
        primes[5] = 11;
      

Alternatively we could create and initialise the array all in a single line:

        var primes = new Array( 1, 2, 3, 5, 7, 11 );
      

To iterate through the array we need an index variable (we'll use i) and a while loop that will keep looping while i is less than the value of the length property of the array. By using the length property in out loop condition we make the loop general, in that it will loop through the whole array no matter the length of the array.

        var i = 0;
        while (i < primes.length)
        {
           document.write("<p> " + primes[i] );
           i++;
        }
      

Discussions of Exercise 3

Constructor functions are named with an initial capital letter, so the following are the names of constructor functions:

  • House

  • MotorCar

The others may be objects, or methods, or property names:

  • door1

  • homeHampus

Discussions of Activity 3

An example of an HTML file resulting in the desired animation could be the following:

<HTML> <HEAD> <SCRIPT>  <!--

////////////////////////////////////////////////////
// function to:
// display image
// increment image number
// increase delay time by 1/4 second
// if not last image then delay and call self
////////////////////////////////////////////////////
function animate()
{
document.noise.src = images[ imageNumber ].src;
imageNumber++;
delay += 250;

if( imageNumber < 4 )
setTimeout( "animate()", delay );

// if imageNumber = 4 the animation has finished
// and this function can terminate
}

///////////////////////////////
// function to:
// set imageNumber for "taptap" image
// set delay to 1/4 second (250 milliseconds)
// execute the animate() function
/////////////////////////////////////////////
function startAnimation()
{
imageNumber = 0;
delay = 250;
animate();
}

// set up image array
var images = new Array( 4 );

images[0] = new Image();
images[0].src = "taptap.gif";
images[1] = new Image();
images[1].src = "knockknock.gif";
images[2] = new Image();
images[2].src = "BANGBANG.gif";
images[3] = new Image();
images[3].src = "silence.gif";

// declare the global variables for the imageNumber and

the delay duration
var imageNumber;
var delay;

//--> </SCRIPT> </HEAD>

<BODY>

<IMG NAME="noise" SRC="silence.gif" onMouseOver="startAnimation()">

</BODY> </HTML>
      

It is important you understand this programme before moving on the later object activities.

Discussions of Activity 4

The object customer1 can be created as follows:

var customer1 = new Object();
      

The properties of this object can be created and assigned as follows:

customer1.name = "fred";
customer1.age = 29;
customer1.creditLimit = 500;
      

A for/in loop to iterate through and display the properties on separate lines could be:

for( var prop in customer1 )
{
 document.write( "<p><b> property </b>" + prop + "<b>  has value </b> " + customer1[ prop ] );
}
      

Discussions of Activity 5

Your constructor function must be named Rectangle. It should take two arguments, named along the lines of newLength and newHeight. The function should assign the value of the first argument to this.length, and the value of the second argument to this.width:

        function Rectangle( newLength, newHeight )
        {
          this.length = newLength;
          this.height = newHeight;
        }
      

Discussions of Activity 6

Your code should set up the three image arrays:

var selected = new Array(3);
selected[0] = new Image();
selected[0].src = "the70s_selected.gif";
selected[1] = new Image();
selected[1].src = "the80s_selected.gif";
selected[2] = new Image();
selected[2].src = "the90s_selected.gif";

var unselected = new Array(3);
unselected[0] = new Image();
unselected[0].src = "the70s_UNselected.gif";
unselected[1] = new Image();
unselected[1].src = "the80s_UNselected.gif";
unselected[2] = new Image();
unselected[2].src = "the90s_UNselected.gif";

var selectedTEXT = new Array(3);
selectedTEXT[0] = new Image();
selectedTEXT[0].src = "the70s_selected_TEXT.gif";
selectedTEXT[1] = new Image();
selectedTEXT[1].src = "the80s_selected_TEXT.gif";
selectedTEXT[2] = new Image();
selectedTEXT[2].src = "the90s_selected_TEXT.gif";
      

Your two functions should look as follows:

function selectImage(imageNumber)
{
var selectStatement = "document." + imageName[imageNumber]

+ ".src = selected[imageNumber].src;";
eval( selectStatement );
document.textArea.src = selectedTEXT[imageNumber].src;
}

function deselectImage(imageNumber)
{
var deselectStatement = "document." + imageName[imageNumber] + ".src = unselected[imageNumber].src;";
eval( deselectStatement );
document.textArea.src = "UNselected_TEXT.gif";
}
      

Your onMouseOver and onMouseOut event one-liners should look similar to the follows:

onMouseOver="selectImage(0);" onMouseOut="deselectImage(0)"
      

(where the 0 should be replaced by the appropriate image number);

Discussions of Activity 7

Your objects with Image properties should be set up in a way similar to the following:

var selected = new Object;
selected.the70s = new Image();
selected.the70s.src = "the70s_selected.gif";
selected.the80s = new Image();
selected.the80s.src = "the80s_selected.gif";
selected.the90s = new Image();
selected.the90s.src = "the90s_selected.gif";

var unselected = new Object();
unselected.the70s = new Image();
unselected.the70s.src = "the70s_UNselected.gif";
unselected.the80s = new Image();
unselected.the80s.src = "the80s_UNselected.gif";
unselected.the90s = new Image();
unselected.the90s.src = "the90s_UNselected.gif";

var selectedTEXT = new Object();
selectedTEXT.the70s = new Image();
selectedTEXT.the70s.src = "the70s_selected_TEXT.gif";
selectedTEXT.the80s = new Image();
selectedTEXT.the80s.src = "the80s_selected_TEXT.gif";
selectedTEXT.the90s = new Image();
selectedTEXT.the90s.src = "the90s_selected_TEXT.gif";
      

Your select and deselect functions can be simplified to the following:

function selectImage(imageName)
{
  document[imageName].src = selected[imageName].src;
  document.textArea.src = selectedTEXT[imageName].src;
}

function deselectImage(imageName)
{
  document[imageName].src = unselected[imageName].src;
  document.textArea.src = "UNselected_TEXT.gif";
}
      

See listing music_associative_arrays.html for a complete HTML file using the above code.

Discussions of Activity 8

Your constructor function should look something like the following:

    function RolloverImage( nameString, selectedIMG, unselectedIMG, selectedTEXT, unselectedTEXT)
    {
      this.name = nameString;
      this.selected = new Image();
      this.selected.src = selectedIMG;
      this.unselected = new Image();
      this.unselected.src = unselectedIMG;
      this.selectedTEXT = new Image();
      this.selectedTEXT.src = selectedTEXT;
      this.unselectedTEXT = new Image();
      this.unselectedTEXT.src = unselectedTEXT;
    }
      

Your two instance methods, and their addition to the prototype should look similar to the following:

    function selectImage()
    {
      // access the IMG NAME by treating 'document' as an associative array

      document[this.name].src = this.selected.src;

      textArea.src = this.selectedTEXT.src;
    }

    function deselectImage()
    {
       // access the IMG NAME by treating 'document' as
       an associative array
       document[this.name].src = this.unselected.src;
       textArea.src = this.unselectedTEXT.src;
    }

    RolloverImage.prototype.select = selectImage;
    RolloverImage.prototype.deselect = deselectImage;
      

The rolloverImages object, and the three properties that are instances of RolloverImage should looks similar to the following:

    var rolloverImages = new Object();

    rolloverImages.the70s = new RolloverImage(
    "the70s",
    "the70s_selected.gif",
    "the70s_UNselected.gif",
    "the70s_selected_TEXT.gif",
    "UNselected_TEXT.gif");

    rolloverImages.the80s = new RolloverImage(
    "the80s",
    "the80s_selected.gif",
    "the80s_UNselected.gif",
    "the80s_selected_TEXT.gif",
    "UNselected_TEXT.gif");

    rolloverImages.the90s = new RolloverImage(
    "the90s",
    "the90s_selected.gif",
    "the90s_UNselected.gif",
    "the90s_selected_TEXT.gif",
    "UNselected_TEXT.gif");
      

Your HTML table should look as follows:

<TABLE CELLSPACING=0 CELLPADDING=0 WIDTH=202 BORDER=0>

<TR>
<TD rowspan = 3>
<IMG NAME="textArea" SRC="UNselected_TEXT.gif">
</TD>

<TD>
<A HREF="the70s.html" onMouseOver="rolloverImages.the70s.select()"

onMouseOut="rolloverImages.the70s.deselect()">
<IMG NAME="the70s" SRC="the70s_UNselected.gif" BORDER=0>
</A>
</TD>
</TR>

<TR>
<TD>
<A HREF="the80s.html" onMouseOver="rolloverImages.the80s.select()"

onMouseOut="rolloverImages.the80s.deselect()">
<IMG NAME="the80s" SRC="the80s_UNselected.gif" BORDER=0>
</A>
</TD>
</TR>

<TR>
<TD>
<A HREF="the90s.html" onMouseOver="rolloverImages.the90s.select()"

onMouseOut="rolloverImages.the90s.deselect()">
<IMG NAME="the90s" SRC="the90s_UNselected.gif" BORDER=0></A>
</TD>
</TR>

</TABLE>
      

Answers to Review Questions

  1. An array is a tabular collection of data, accessed via a numeric index. Each element of an array can be a primitive value, or a reference to an object (possible another Array object).

  2. The number 4 is the index of the 5th element in the array (remember the first element is stored in array element myArray[0]). The index of an array states the element to which it is being referred.

  3. There are 3 elements in this array. They are:

            ages[0]
            ages[1]
            ages[2]
    	  

    (remember, arrays are indexed with 0 as the first element index, not 1.)

  4. Simple numeric variables like a1 and b1 store values, and when the value of variable a1 is assigned to the value of b1, a copy of the value 5 is placed into variable b1, When b1 changes the value it stores this has no effect on the number 5 stored elsewhere in memory in variable a1.

    Array variables contain a reference to the location in memory where the array elements are stored. Copying an array variable means copying the reference, so in the above code variable b2 is referring to the same array as a2, therefore changing the array elements referred to by b2 will also change the elements referred to by a2.

  5. In this statement document is a variable that contains a reference to the document instance of the Document constructor. When a browser loads and interprets an HTML file containing JavaScript, it creates a single instance based on Document, called document. This object is made available as a property of the global object to JavaScript programmers, so that they can refer to the properties and methods of browser document.

  6. The answer is that triangle1.width has a value of 5. This is because when t2 is assigned the value of triangle1, it is assigned the reference to triangle1. So when a change is made to the object referred to by t2, this is also the object referred to by traingle1.

    Browser output is as follows:

  7. Yes they are. In fact more so that for many other object languages, since methods are just another form of data.

Contribution to Discussion Topics

  1. Yes this statement is true — associative arrays and objects are the same thing. Looking at objects as associative arrays, however, provides a potentially more flexible and dynamic way to access properties and methods.

    However, associative arrays should be distinguished from numerically indexed arrays, the latter having an explicit order to their elements.

  2. When a prototype changes, the changes are inherited by all objects sharing the prototype at that point in time. Therefore if an object was previously created and used, and then its prototype changed, performing the same operations on the object will not necessarily result in the same behaviour. This could lead to inconsistent software system behaviour, and might be a very difficult bug to locate and repair.

    Few circumstances exist where one might desire such changing behaviour from objects in the middle of execution of a programme.