Java Reference
In-Depth Information
The expression written to the page is the concatenation of the value of the greetingString variable, a
space ( " " ), the value of the myName variable, and the HTML <br/> element, which causes a line break.
For example, if you enter Jeremy into the prompt box, the value of this expression will be as follows:
Hello Jeremy<br/>
In the next line of code is a similar expression. This time it is just the concatenation of the value in the
variable greetingString , a space, and the value in the variable myName . You store the result of this
expression in the variable concatString . Finally, you write the contents of the variable concatString
to the page using document.write() :
concatString = greetingString + " " + myName;
document.write(concatString);
mixing numbers and strings
What if you want to mix text and numbers in an expression? A prime example of this would be
in the temperature converter you saw earlier. In the example, you just display the number without
telling the user what it actually means. What you really want to do is display the number with
descriptive text wrapped around it, such as “The value converted to degrees centigrade is 10.”
Mixing numbers and text is actually very easy. You can simply join them using the + operator.
JavaScript is intelligent enough to know that when both a string and a number are involved, you're not
trying to do numerical calculations, but rather that you want to treat the number as a string and join it to
the text. For example, to join the text My age is and the number 101 , you could simply do the following:
alert("My age is " + 101);
This would produce an alert box with “My age is 101” inside it.
Making the Temperature Converter User‐Friendly
trY it out
You can try out this technique of concatenating strings and numbers in the temperature‐converter
example. You output some explanatory text, along with the result of the conversion calculation. The
changes that you need to make are very small, so load ch2 _ example4.html into your text editor and
change the following line. Then save it as ch2 _ example6.html .
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 6</title>
</head>
<body>
<script>
// Equation is °C = 5/9 (°F - 32).
var degFahren = prompt("Enter the degrees in Fahrenheit",50);
 
Search WWH ::




Custom Search