Day 7: Arrays/Random Number Generator
Arrays: There are times that we want to create groups
of variables, but don't want to (or won't be able to) take the
time and trouble to name each variable. For this purpose, we can
create groups of related variables called Arrays.
Creating an array, and putting values into the related variables
var myArray = new Array();
myArray = "Huey";
myArray = "Dewey";
myArray = "Louie";
var myOutput = "Donald's nephews
for(var x = 0; x < myArray.length;
myOutput += "
" + myArray[x];
The array is declared as an object, and must use the keyword
"new". The word array is a control word, and must be
capitalized. The parentheses after the word array allow us to
indicate the number of elements (items) in the array. If we leave
it empty, the array is made longer as we add more items.
The items are added as "elements" of the array, and
are associated with a number, starting at zero. Zero based arrays
can be confusing, but since computers all start to count at zero,
the first number, making 9 the 10th number in our decimal numbering
system. The example above uses a for loop to show all the elements
in the array in an alert. Note that the element of the array can
be accessed one at a time, using the array number, in this case
x represents the number.
We are able to easily add or subtract items from our array, and
to be able to keep the code consistent in this way.
Random Numbers: To be able to have more fun with arrays,
we will first use the following function to generate random numbers:
var myNum = Math.floor(Math.random()*(n+1));
var myRandomNum = randomNum(5);
alert("My random number is: "
a random number. Our function "encapsulates" (wraps)
it's abilities. When we use it to generate a random number, we
only need to declare a variable, and equate it to the function,
and pass a number into the function (in this case 5). This will
generate a random number between 0 and 5. The number passed to
the function will be the maximum.
Once we have generated a random number, we can use this number
with an array to display a random "message of the day"
or in our case, a "quote" to display to the user:
myNum++var quoteArray = new Array();
quoteArray = "A stitch in time
quoteArray = "Four score and 7 years ago.";
quoteArray = "For whom the bell tolls.";
quoteArray = "There once was a man from Calcutta.";
quoteArray = "To thine own self be true";
var x = randomNum(5);
alert("Today's quote is: "
This code is useful for generating random script, or images,
so the user sees more dynamic page content on your site. We will
work later with date oriented code, since content that appears
or disappears on subsequent reloads of a page could be annoying
to a user. That would make this code more useful for an image
swap, for example, for an advertisement, etc.