LEARNING JAVASCRIPT - Trang 110

problems and pitfalls with the abstract equality operator, I recommend Douglas

Crockford’s book,

JavaScript: The Good Parts

(O’Reilly).

Most of the problematic behavior of the abstract equality operators

surrounds the values null, undefined, the empty string, and the

number 0. For the most part, if you are comparing values that you

know not to be one of these values, it’s generally safe to use the

abstract equality operator. However, don’t underestimate the power

of rote habit. If you decide, as I recommend, to use the strict equal‐

ity operator by default, then you never have to think about it. You

don’t have to interrupt your thought flow to wonder whether it’s

safe or advantageous to use the abstract equality operator; you just

use the strict equality operator and move on. If you later find that

the strict equality operator isn’t producing the right result, you can

do the appropriate type conversion instead of switching to the

problematic abstract equality operator. Programming is hard

enough: do yourself a favor, and avoid the problematic abstract

equality operator.

Here are some examples of strict and abstract equality operators in use. Note that

even though objects

a

and

b

contain the same information, they are distinct objects,

and are neither strictly or abstractly equal:

const

n

=

5

;

const

s

=

"5"

;

n

===

s

;

// false -- different types

n

!==

s

;

// true

n

===

Number

(

s

);

// true -- "5" converted to numeric 5

n

!==

Number

(

s

);

// false

n

==

s

;

// true; not recommended

n

!=

s

;

// false; not recommended

const

a

=

{

name

:

"an object"

};

const

b

=

{

name

:

"an object"

};

a

===

b

;

// false -- distinct objects

a

!==

b

;

// true

a

==

b

;

// false; not recommended

a

!=

b

;

// true; not recommended

Relational operators compare values in relation to one another, and they only make

sense for data types that have a natural ordering, such as strings (“a” comes before

“b”) and numbers (0 comes before 1). The relational operators are less than (

<

), less

than or equal to (

<=

), greater than (

>

), and greater than or equal to (

>=

):

3

>

5

;

// false

3

>=

5

;

// false

3

<

5

;

// true

3

<=

5

;

// true

86 | Chapter 5: Expressions and Operators

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.