LEARNING JAVASCRIPT - Trang 77

const

a

=

parseInt

(

"16 volts"

,

10

);

// the " volts" is ignored, 16 is

// parsed in base 10

const

b

=

parseInt

(

"3a"

,

16

);

// parse hexadecimal 3a; result is 58

const

c

=

parseFloat

(

"15.5 kph"

);

// the " kph" is ignored; parseFloat

// always assumes base 10

A

Date

object can be converted to a number that represents the number of millisec‐

onds since midnight, January 1, 1970, UTC, using its

valueOf()

method:

const

d

=

new

Date

();

// current date

const

ts

=

d

.

valueOf

();

// numeric value: milliseconds since

// midnight, January 1, 1970 UTC

Sometimes, it is useful to convert boolean values to 1 (true) or 0 (false). The conver‐

sion uses the conditional operator (which we will learn about in

Chapter 5

):

const

b

=

true

;

const

n

=

b

?

1

:

0

;

Converting to String

All objects in JavaScript have a method

toString()

, which returns a string represen‐

tation. In practice, the default implementation isn’t particularly useful. It works well

for numbers, though it isn’t often necessary to convert a number to a string: that con‐

version usually happens automatically during string concatenation or interpolation.

But if you ever do need to convert a number to a string value, the

toString()

method

is what you want:

const

n

=

33.5

;

n

;

// 33.5 - a number

const

s

=

n

.

toString

();

s

;

// "33.5" - a string

Date

objects implement a useful (if lengthy)

toString()

implementation, but most

objects will simply return the string

"[object Object]"

. Objects can be modified to

return a more useful string representation, but that’s a topic for

Chapter 9

. Arrays,

quite usefully, take each of their elements, convert them to strings, and then join

those strings with commas:

const

arr

=

[

1

,

true

,

"hello"

];

arr

.

toString

();

// "1,true,hello"

Converting to Boolean

In

Chapter 5

, we’ll learn about JavaScript’s idea of “truthy” and “falsy,” which is a way

of coercing all values to true or false, so we won’t go into all those details here. But we

will see that we can convert any value to a boolean by using the “not” operator (

!

)

twice. Using it once converts the value to a boolean, but the opposite of what you

want; using it again converts it to what you expect. As with numeric conversion, you

Data Type Conversion | 53