Page 14
Functions with More Than 1 Parameter
Here are the arrays I've defined:
var monkeys = new Array("mattmarg","wendy","kristin","tim","aaron", "luke");
var kittyphile = new Array("wendy", "ruby", "roscoe", "tim");
var discophile = new Array("mattmarg", "john travolta", "wendy");
var happy = new Array("tim", "wendy", "stimpy", "aaron");
var cranky = new Array("ren", "mattmarg","luke");
With these arrays defined, and the arrayIntersect function written, it's very easy to figure out which Webmonkeys love disco: dancing monkeys.
Note that even though John Travolta loves disco, he's not on the monkeys list, so he's not a dancing monkey. To call this function, I wrote this:
<a href="#" onClick="arrayIntersect('dancing monkeys',monkeys,discophile); return false;">dancing monkeys</a>
This is a function with three parameters: a string representing the name of the intersection, the first array, and the second array. It's similarly easy to find the names of Webmonkeys who like cats: cat-loving monkeys.
Like so:
<a href="#" onClick="arrayIntersect('monkeys who love cats',monkeys,kittyphile); return false;">cat-loving monkeys</a>
Let's look at the arrayIntersect function itself:
function arrayIntersect(intersect_name, array_1, array_2)
{
var the_list = "";
for (var loop_1 = 0; loop_1 < array_1.length; loop_1++)
{
for (var loop_2 = 0; loop_2 < array_2.length; loop_2++)
{
if (array_1[loop_1] == array_2[loop_2])
{
the_list = the_list + array_1[loop_1] + " ";
}
}
}
alert("the " + intersect_name + " are: "+ the_list);
}
See if you can figure out for yourself what the for loops are doing in this example. The important thing to note here is the first line of the function:
function arrayIntersect(intersect_name, array_1, array_2)
This defines a function called arrayIntersect with three parameters. Just like in the earlier example, each parameter is like a variable that gets set when the function is called. So, when this function is called like this:
arrayIntersect('dancing monkeys',monkeys,discophile);
The following assignments are made:
- intersect_name = 'dancing monkeys'
- array_1 = monkeys
- array_2 = discophile
The only thing you have to be careful of is that you call your functions with the right number of parameters. If we had accidentally called arrayIntersect like this:
arrayIntersect(monkeys,discophile);
We would have gotten all kinds of errors. Try it and see what happens.
Functions are the basic building blocks of any decent JavaScript, so it's very important that you understand how they work. Here's an exercise to test your knowledge of functions. After you've done the exercise, we'll do one more exercise that combines everything we've learned in this lesson, and then go on to do some more work on our personal browsers.
next page»
|