LEARNING JAVASCRIPT - Trang 76

6

Normally, you wouldn’t use a constructor without the

new

keyword, which we’ll learn about in

Chapter 9

; this

is a special case.

// extremely simple email recognizer

const

email

=

/\b[a-z0-9._-]+@[a-z_-]+(?:\.[a-z]+)+\b/

;

// US phone number recognizer

const

phone

=

/(:?\+1)?(:?\(\d{3}\)\s?|\d{3}[\s-]?)\d{3}[\s-]?\d{4}/

;

Maps and Sets

ES6 introduces the data types

Map

and

Set

, and their “weak” counterparts,

WeakMap

and

WeakSet

. Maps, like objects, map keys to values, but offer some advantages over

objects in certain situations. Sets are similar to arrays, except they can’t contain dupli‐

cates. The weak counterparts function similarly, but they make functionality trade-

offs in exchange for more performance in certain situations.
We will cover maps and sets in

Chapter 10

.

Data Type Conversion

Converting between one data type and another is a very common task. Data that

comes from user input or other systems often has to be converted. This section covers

some of the more common data conversion techniques.

Converting to Numbers

It’s very common to want to convert strings to numbers. When you collect input from

a user, it’s usually as a string, even if you’re collecting a numeric value from them.

JavaScript offers a couple of methods to convert strings to numbers. The first is to use

the

Number

object constructor:

6

const

numStr

=

"33.3"

;

const

num

=

Number

(

numStr

);

// this creates a number value, *not*

// an instance of the Number object

If the string can’t be converted to a number,

NaN

will be returned.

The second approach is to use the built-in

parseInt

or

parseFloat

functions. These

behave much the same as the

Number

constructor, with a couple of exceptions. With

parseInt

, you can specify a radix, which is the base with which you want to parse the

number. For example, this allows you to specify base 16 to parse hexadecimal num‐

bers. It is always recommended you specify a radix, even if it is 10 (the default). Both

parseInt

and

parseFloat

will discard everything they find past the number, allowing

you to pass in messier input. Here are examples:

52 | Chapter 3: Literals, Variables, Constants, and Data Types

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.