Java Reference
In-Depth Information
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-7.
This example is identical to ch2 _ example4.html , except for one line:
alert(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade");
So we will just look at this line here. You can see that
the alert() function contains an expression. Let's
look at that expression more closely.
First is the variable degFahren , which contains
numerical data. You concatenate that to the string
"\xBO Fahrenheit is ". JavaScript realizes that
because you are adding a number and a string, you
want to join them into one string rather than trying
to take their sum, and so it automatically converts the
number contained in degFahren to a string. You next
concatenate this string to the variable degCent , containing numerical data. Again JavaScript converts
the value of this variable to a string. Finally, you concatenate to the string "\xBO centigrade" .
Note also the escape sequence used to insert the degree character into the strings. You'll remember
from earlier in the chapter that you can use \x NN to insert special characters not available to type in
directly. ( NN is a hexadecimal number representing a character from the Latin‐1 character table.) So
when JavaScript spots \xB0 in a string, instead of showing those characters it does a lookup to see what
character is represented by B0 and shows that instead.
Something to be aware of when using special characters is that they are not necessarily cross‐platform-
compatible. Although you can use \x NN for a certain character on a Windows computer, you may find
you need to use a different character on a Mac or a Unix machine.
You look at more string manipulation techniques in Chapter 5—you see how to search strings and insert
characters in the middle of them, and in Chapter 6 you see some very sophisticated string techniques.
figure 2-7  
data tYpe Conversion
As you've seen, if you add a string and a number, JavaScript makes the sensible choice and converts
the number to a string, then concatenates the two. Usually, JavaScript has enough sense to make
data type conversions like this whenever it needs to, but in some situations you need to convert the
 
Search WWH ::




Custom Search