CS 101 - Lab 9
Due at the end of lab session
during the 10th week
Arrays
This week we are going to look at arrays in JavaScript
and some typical operations performed on arrays. This will also allow us to use the for loop. There are three ways to create an array:
• arrayName = new Array ()
• arrayName = new Array (arrayLength)
• arrayName = new Array (firstValue,
secondValue, ... , lastValue)
The first method creates an array but the number of
elements in the array (which is also called the length) is unknown. As elements are added into the array the
length of the array is modified. This
type of array usage is very uncommon in other languages, so we won't discuss
it.
The second and third methods are much more common. The second method creates a array of length
of "arrayLength" but no values are stored into the array. The third value create and initializes an
array. The length of the array is equal
to the number of values listed.
Lab Assignment
Turn
in the JavaScript/HTML code that does the following to the Digital Drop Box:
Create a JavaScript program that has one button and 6
text fields. When the button is clicked
perform the following tasks:
• Generate 10 random numbers and store them
into an array (see below).
• Calculate the average of the array values
and display that in the first text field.
• Determine the smallest value in the array
and display it in the second text field.
• Determine the largest value in the array
and display it in the third text field.
• Determine the number of array values that
are equal to the average and display that number in the fourth text field.
• Determine the number of array values that
are less than the average and display that number in the fifth text field.
• Determine the number of array values that
are greater than the average and display that number in the sixth text field.
Remember that the subscript values for the array (also
called the index values) start with the value of zero and end with the length
of the array - 1. So an array with
length of 10 has it subscript values in the range of 0 to 9.
When writing your code, the easiest way to do this is to
use a for loop. Set up the for loop so
that the loop variable has the value of a different subscript each time through
the loop. The loop variable can then be
used to access one element in the array each time though the loop. For example the following code will store 10
different random numbers in an array of length 10. Note the declaration of variables is not shown.
//
generate 10 random numbers and store them in "array"
for (i = 0; i < 10; i++)
{
array[i] = Math.random()
}