Java Reference
In-Depth Information
document.write("Value " + loopCounter +
" was " + degFahren[loopCounter] +
" degrees Fahrenheit");
document.write(" which is " + degCent[loopCounter] +
" degrees centigrade<br />");
}
</script>
</body>
</html>
When you load this page into your browser, you should see exactly the same results that you had with
ch3 _ example4.html .
At the top of the script block you declare your convertToCentigrade() function. You saw this
function earlier:
function convertToCentigrade(degFahren) {
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
If you're using a number of separate script blocks in a page, it's very important that the
function be defined before any script calls it. If you have a number of functions, you may want to
put them all in their own script file and load it before all other scripts. That way you know where
to find all your functions, and you can be sure that they have been declared before they have
been used.
You should be pretty familiar with how the code in the function works. You declare a variable
degCent , do your calculation, and then return degCent back to the calling code. The function's
parameter is degFahren , which provides the information the calculation needs.
Following the function declaration is the code that executes when the page loads. First you define the
variables you need, and then you have the two loops that calculate and then output the results. This is
mostly the same as before, apart from the first for loop:
for (loopCounter = 0; loopCounter <= 2; loopCounter++) {
degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
}
The code inside the first for loop puts the value returned by the function convertToCentigrade() into
the degCent array.
There is a subtle point to the code in this example. Notice that you declare the variable degCent
within your function convertToCentigrade() , and you also declare it as an array after the function
definition.
Surely this isn't allowed?
Well, this leads neatly to the next topic of this chapter—scope.
Search WWH ::




Custom Search