Let's suppose we send the function a color...
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT language="Javascript"><!--
colors = new Array();
colors[0] = "red";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "yellow";
colors[4] = "purple";
colors[5] = "orange";
function GetMyColor(mycolor)
{
alert(colors[mycolor]);
}
//--></SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript:GetMyColor(3)">Click here for my color</A>
</BODY>
</HTML>
Try it.
Exercise: Add a prompt box to the last example to get a number from a
user. Ask the user for a number between 0 and 5. Use that number to grab an
element from the array. (Technically I suppose we would ask for an integer between
and including 0 and 5, but that sounds confusing. We'll just keep it a number
between 0 and 5 and figure we all understand what we're talking about.)
Exercise: Add to your last exercise an if-else statement that catches
any entry greater than 5 and asks again for a number between 0 and 5.
Notice that the last couple examples hard code the number 5 into the function.
If we were to add colors, we would have to go through the function and change
all references to "5". Hey, here's an idea... let's get that number
into a variable...
Exercise: Use the length property of an array to get the number of elements
into a variable, then use that variable in the function. This is a tough exercise.
Make sure you test your script thoroughly to reveal any errors.
I suppose this is a good time for a little side track. Our latest script checks
if a number is greater than 5 (or whatever). This script could also benefit
from a bit that checks if the number is less than 0. In other words check if
the number is greater than 5 OR less than 0.
Consider this simple if statement...
if (x > 5)
{
do something
}
It checks to see if x is greater than five. We can add another condition and
test if x > 5 or x < 0...
if ((x > 5)||(x <
0))
{
do something
}
The OR operator is two vertical slashes (pipes)... ||.
Exercise: Add this feature to your last exercise. Make the script check
if the number is not greater than 5 or less than 0.
Similar to the OR operator is the AND operator. This operator is two ampersands...
&&
if ((x > 5)&&(x < 0))
{
do something
}
The above basically says if x is greater than 5 and x is less than 0 then do
something. Obviously no number can fit these conditions, but hopefully you still
understand the concept.
Exercise: Write a small script from scratch. When the user clicks on
a link a prompt box is thrown up that asks for a particular number, (such as
"Please enter 4"). A second prompt box then comes up asking for a
second number. The script is to determine if the first number is correct and
the second number is correct. If correct, the user gets rewarded with a positive
message, if not, a negative message. Utilize the && operator in your
solution. Hint: remember to test for equality using a double equal sign ==.
Next>> | ||||||||||||||||||||||||||||||||
|