Java Reference
In-Depth Information
Dealing with Strings That Won't Convert
Some strings simply are not convertible to numbers, such as strings that don't contain any numerical
data. What happens if you try to convert these strings? As a little experiment, try changing the preced-
ing example so that myString holds something that is not convertible. For example, change the line
var myString = “56.02 degrees centigrade”;
to
var myString = “I'm a name not a number”;
Now reload the page in your browser and you should see what's shown in Figure 2-10.
“I'm a name not a number” is NaN as an integer
“I'm a name not a number” when converted to an integer equals NaN
“I'm a name not a number” when converted to a floating point number equals NaN
Figure 2-10
You can see that in the place of the numbers you got before, you get NaN . What sort of number is that?
Well, it's Not a Number at all!
If you use parseInt() or parseFloat() with any string that is empty or does not start with at least
one valid digit, you get NaN , meaning Not a Number.
NaN is actually a special value in JavaScript. It has its own function, isNaN() , which checks whether
something is NaN or not. For example,
myVar1 = isNaN(“Hello”);
will store the value true in the variable myVar1 , since “Hello” is not a number, whereas
myVar2 = isNaN(“34”);
will store the value false in the variable myVar2 , since 34 can be converted successfully from a string
to a number by the isNaN() function.
In Chapter 3 you'll see how you can use the isNaN() function to check the validity of strings as num-
bers, something that proves invaluable when dealing with user input, as you'll see in Chapter 7.
Arrays
Now we're going to look at a new concept — something called an array . An array is similar to a normal
variable, in that you can use it to hold any type of data. However, it has one important difference, which
you'll see in this section.
Search WWH ::




Custom Search