Java Reference
In-Depth Information
Mixing numbers and text is actually very easy. You can simply join them together using the + opera-
tor. 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.
Try It Out Making the Temperature Converter User-Friendly
You can try out this technique of concatenating strings and numbers in our temperature-converter
example. You'll 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_examp4.htm into your text editor and
change the following line. Then save it as ch2_examp6.htm.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
var degFahren = prompt(“Enter the degrees in Fahrenheit”, 50);
var degCent;
degCent = 5/9 * (degFahren - 32);
alert(degFahren + “\xB0 Fahrenheit is “ + degCent + “\xB0 centigrade”);
</script>
</body>
</html>
Load the page into your web browser. Click OK in the prompt box to submit the value 50 , and this time
you should see the box shown in Figure 2-8.
Figure 2-8
This example is identical to ch2_examp4.htm , except for one line:
alert(degFahren + “\xB0 Fahrenheit is “ + degCent + “\xB0 centigrade”);
Search WWH ::




Custom Search