Tải bản đầy đủ (.pdf) (19 trang)

Data Types and Values

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (187.67 KB, 19 trang )

Chapter 3. Data Types and Values
Computer programs work by manipulating values , such as the number 3.14 or the text
"Hello World". The types of values that can be represented and manipulated in a
programming language are known as data types, and one of the most fundamental
characteristics of a programming language is the set of data types it supports. JavaScript
o
imitive data types, JavaScript supports a composite data type
known as object. An object (that is, a member of the data type object) represents a
er primitive values, like numbers and strings, or composite
s). Objects in JavaScript have a dual nature: an object can
d to perform
we'll treat the function data type independently of the object and array types.
ds
e
ul pattern-matching tool described in Chapter 10
allows you to work with three primitive data types: numbers, strings of text (known as
"strings"), and boolean truth values (known as "booleans"). JavaScript also defines tw
trivial data types, null and undefined, each of which defines only a single value.
In addition to these pr
collection of values (eith
values, like other object
represent an unordered collection of named values or an ordered collection of numbered
values. In the latter case, the object is called an
array . Although objects and arrays are
fundamentally the same data type in JavaScript, they behave quite differently and will
usually be considered distinct types throughout this book.
JavaScript defines another special kind of object, known as a function . A function is an
object that has executable code associated with it. A function may be invoke
some kind of operation. Like arrays, functions behave differently from other kinds of
objects, and JavaScript defines special language syntax for working with them. Thus,
In addition to functions and arrays, core JavaScript defines a few other specialized kin


of objects. These objects do not represent new data types, just new classes of objects. Th
Date class defines objects that represent dates, the RegExp class defines objects that
represent regular expressions (a powerf
),
and the Error class defines objects that represent syntax and runtime errors that can occur
introduces the object, array, and function data types, which are fully documented in
apter 7
in a JavaScript program.
The remainder of this chapter documents each of the primitive data types in detail. It also
Ch , Chapter 8, and Chapter 9. Finally, it provides an overview of the Date,
d Error classes, which are documented in full detail in the core reference
is book.
t
ing-point values. JavaScript represents numbers using the 64-bit
floating-point format defined by the IEEE 754 standard,
[1]
RegExp, an
ection of ths
3.1 Numbers
Numbers are the most basic data type; they require very little explanation. JavaScript
differs from programming languages such as C and Java in that it does not make a
distinction between integer values and floating-point values. All numbers in JavaScrip
are represented as float
which means it can represent
numbers as large as ±1.7976931348623157 x 10
308
and as small as ±5 x 10
-324.
lmost all
teral can be preceded by a minus sign (-) to make the

gation operator (see Chapter 5
[1]
This format should be familiar to Java programmers as the format of the double type. It is also the double format used in a
modern implementations of C and C++.
When a number appears directly in a JavaScript program, we call it a numeric literal.
JavaScript supports numeric literals in several formats, as described in the following
sections. Note that any numeric li
number negative. Technically, however, - is the unary ne ),
3.1.1 Integer Literals
e:
ular the bitwise operators described in
not part of the numeric literal syntax.
In a JavaScript program, a base-10 integer is written as a sequence of digits. For exampl
0
3
10000000
The JavaScript number format allows you to exactly represent all integers between -
9007199254740992 (-2
53
) and 9007199254740992 (253), inclusive. If you use integer
values larger than this, you may lose precision in the trailing digits. Note, however, that
certain integer operations in JavaScript (in partic
Chapter 5) are performed on 32-bit int
2147483647 (2
egers, which range from -2147483648 (-2
31
) to
gnizes hexadecimal (base-16)
31
-1).

3.1.2 Hexadecimal and Octal Literals
In addition to base-10 integer literals, JavaScript reco
values. A hexadecimal literal begins with "0x" or "0X", followed by a string of
hexadecimal digits. A hexadecimal digit is one of the digits 0 through 9 or the letters a (or
A) through f (or F), which are used to represent values 10 through 15. Examples of
hexadecimal integer literals are:
0xff // 15*16 + 15 = 255
0xCAFE911
(base 10)
lthough the ECMAScript standard does not support them, some implementations of
in octal (base-8) format. An octal literal
A
JavaScript allow you to specify integer literals
begins with the digit 0 and is followed by a sequence of digits, each between 0 and 7. For
7 = 255 (base 10)
example:
0377 // 3*64 + 7*8 +
write an integer literal with a leading zero -- you cannot know whether an implementation
real
e is represented as the integral part of the number, followed by a
decimal point and the fractional part of the number.
Floating-point literals may also be represented using exponential notation: a real number
For example:
2345.789
1.4738223E-32 // 1.4738223 x 10
-32
Note that there are infinitely many real numbers, but only a finite number of them
mbers in
JavaScript, the representation of the number will often be an approximation of the actual
Numbers

ithmetic operators that the language
on,
* for multiplication, and / for
r arithmetic operators can be found in Chapter 5
will interpret it as an octal or decimal value.
3.1.3 Floating-Point Literals
Floating-point literals can have a decimal point; they use the traditional syntax for
numbers. A real valu
followed by the letter e (or E), followed by an optional plus or minus sign, followed by
an integer exponent. This notation represents the real number multiplied by 10 to the
power of the exponent.
More succinctly, the syntax is:
[digits][.digits][(E|e)[(+|-)]digits]
3.14
.333333333333333333
6.02e23 // 6.02 x 10
23
(18437736874454810627, to be exact) can be represented exactly by the JavaScript
floating-point format. This means that when you're working with real nu
number. The approximation is usually good enough, however, and this is rarely a
practical problem.
3.1.4 Working with
JavaScript programs work with numbers using the ar
rovides. These include
+ for addition, - for subtractip
division. Full details on these and othe .
matical functions that are a core
all stored as properties of a
Math to access them. For example,
here's how to compute the sine of the numeric value

x:
In addition to these basic arithmetic operations, JavaScript supports more complex
mathematical operations through a large number of mathe
part of the language. For convenience, these functions are
ingle Math object, so we always use the literal name s
sine_of_x = Math.sin(x);
th.sqrt(x*x + y*y);
ng( )
var x = 33;
var y = x.toString(2); // y is "100001"
To invoke th ( ) method on a number literal,
prevent the . al point:
y = (257).toString(0x10);
3.1.5 Special Numeric Values
point value becomes
est representable finite num
nit becomes lower
t tive d as -
nfinity
l to any number, including itself! For this reason, a
special function, isNaN( ), is required to test for this value. A related function,
sFinite( ) , tests whether a number is not NaN and is not positive or negative infinity.
And to compute the square root of a numeric expression:
hypot = Ma
See the Math object and subsequent listings in the core reference section of this book for
full details on all the mathematical functions supported by JavaScript.
There is also one interesting method that you can use with numbers. The toStri
method converts an integer to a string, using the radix, or base, specified by its argument
(the base must be between 2 and 36). For example, to convert a number to binary, use
toString( ) like this:

e toString
from being interpreted as a decim
you can use parentheses to
var // y is "101"
JavaScript uses several special num
larger than the larg
eric values. When a floating-
ber, the result is a special infinity value,
which JavaScript prints as Infi y. Similarly, when a negative value
han the last representable nega
.
number, the result is negative infinity, printe
I
Another special JavaScript numeric value is returned when a mathematical operation
(such as division of zero by zero) yields an undefined result or an error. In this case, the
result is the special not-a-number value, printed as
NaN. The not-a-number value behaves
unusually: it does not compare equa
i
Table 3-1 lists several constants that JavaScript defines to represent these special numeric
values.
Table 3-1. Special numeric constants
Constant Meaning
Infinity
Special value to represent infinity
NaN
Special not-a-number value
Number.MAX_VALUE
Largest representable number
Number.MIN_VALUE

Smallest (closest to zero) representable number
Number.NaN
Special not-a-number value
Number.POSITIVE_INFINITY
Special value to represent infinity
Number.NEGATIVE_INFINITY
Special value to represent negative infinity
The Infinity and NaN constants are defined by the ECMAScript v1 standard and are not
JavaScript 1.3. The various Number constants, however, have been
marks. Note that JavaScript does not have a character data type such as char,
like C, C++, and Java do. To represent a single character, you simply use a string that has
A string is a sequence of zero or more Unicode characters enclosed within single or
gle line;
3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"
"This string\nhas two lines"
"pi is the ratio of a circle's circumference to its diameter"
implemented prior to
implemented since JavaScript 1.1.
3.2 Strings
A string is a sequence of Unicode letters, digits, punctuation characters, and so on -- it is
the JavaScript data type for representing text. As you'll see shortly, you can include string
literals in your programs by enclosing them in matching pairs of single or double
quotation
a length of 1.
3.2.1 String Literals
double quotes (' or "). Double-quote characters may be contained within strings
delimited by single-quote characters, and single-quote characters may be contained
within strings delimited by double quotes. String literals must be written on a sin

they may not be broken across two lines. If you need to include a newline character in a
string literal, use the character sequence
\n , which is documented in the next section.
Examples of string literals are:
"" // The empty string: it has zero characters
'testing'
"
As illustrated in the last example string shown, the ECMAScript v1 standard allows
Unicode characters within string literals. Implementations prior to JavaScript 1.3,
however, typically support only ASCII or Latin-1 characters in strings. As we'll see
next section, de
in the
you can also inclu Unicode characters in your string literals using special
"escape sequences." This is useful if your text editor does not provide complete Unicode
).
aScript code often contains strings of HTML
code, and HTML code often contains strings of JavaScript code. Like JavaScript, HTML
strings. Thus, when combining
vaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the
3
h
ble
hat represents a newline
character.
[2]
support.
Note that when you use single quotes to delimit your strings, you must be careful with
English contractions and possessives like can't and O'Reilly's. Since the apostrophe is the
same as the single-quote character, you must use the backslash character (\) to escape
any apostrophes that appear in single-quoted strings (this is explained in the next section

In client-side JavaScript programming, Jav
uses either single or double quotes to delimit its
Ja
other style for HTML. In the following example, the string "Thank you" is single-quoted
within a JavaScript expression, which is double-quoted within an HTML event handler
attribute:
<a href="" onclick="alert('Thank you')">Click Me</a>
.2.2 Escape Sequences in String Literals
The backslash character (\) has a special purpose in JavaScript strings. Combined wit
the character that follows it, it represents a character that is not otherwise representa
within the string. For example, \n is an escape sequence t
[2]
C, C++, and Java programmer
ample, mentioned in the pr cape, which represents
single q This escape sequence is useful when you need
nclude a hat is contained within single quotes. You can
why we ences -- here, the backslash allows us to escape from
acter. Instead of using it to mark the end
he string e:
le 3-2
s will already be familiar with this and other JavaScript escape sequences.
Another ex evious section, is the \' es
the
to i
uote (or apostrophe) character.
n apostrophe in a string literal t
see
the usual interpretation of the single-quote char
call these escape sequ
of t , we use it as an apostroph

'You\'re right, it can\'t be a quote'
Tab li pe sequences and the characters they represent. Two of
escape s that can be used to represent any character by
ode as a hexadecimal number. For example,
sts the JavaScript esca
the
specifying its Latin-1 or Unicode character c
equences are generic ones
the sequence \xA9 represents the copyright symbol, which has the Latin-1 encoding
given by the hexadecimal number A9. Similarly, the \u escape represents an arbitrary
Unicode character specified by four hexadecimal digits. \u03c0 represents the character
, for example. Note that Unicode escapes are required by the ECMAScript v1 standard
are not lementations prior to JavaScript 1.3. Some
mentations of JavaScript also allow a Latin-1 character to be specified by three
al digits equence is not supported in the
MAScri uld no longer be used.
but
imple
typically supported in imp
oct following a backslash, but this escape s
EC pt v3 standard and sho
Table 3-2. JavaScript escape sequences
Sequence Character represented
\0
The NUL character (\u0000).
\b
Backspace (\u0008).
\t
Horizontal tab (\u0009).
\n

Newline (\u000A).
\v
Vertical tab (\u000B).
\f
Form feed ( ).\u000C
\r
Carriage return (\u000D).
\"
Double quote (\u0022).
\'
Apostrophe or single quote (\u0027).
\\
Backslash (\u005C).
\xXX
The Latin-1 character specified by the two hexadecimal digits XX.
\uXXXX
The Unicode character specified by the four hexadecimal digits XXXX.
\XXX
The Latin-1 character specified by the octal digits XXX, between 1 and 37
Not supported by ECMAScript v3; do not use this escape sequence.
7.
Finally, note that the backslash escape cannot be used before a line break to continue a
ring (or other JavaScript) token across two lines or to include a literal line break in a st
string. If the \ character precedes any character other than those shown in Table 3-2, the
backslash is simply ignored (although future versions of the language may, of course
define new escape sequences). For exam
,
ple, \# is the same thing as #.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×