LEARNING JAVASCRIPT - Trang 112

let

n

=

0

;

while

(

true

) {

n

+=

0.1

;

if

(

Math

.

abs

(

n

-

0.3

)

<

Number

.

EPSILON

)

break

;

}

console.log(

`Stopped at

${

n

}

`

);

Notice we subtract our target (0.3) from our test number (

n

) and take the absolute

value (using

Math.abs

, which we’ll cover in

Chapter 16

). We could have done an eas‐

ier calculation here (for example, we could have just tested to see if

n

was greater than

0.3), but this is the general way to determine if two doubles are close enough to be

considered equal.

String Concatenation

In JavaScript, the

+

operator doubles as numeric addition and string concatenation

(this is quite common; Perl and PHP are notable counterexamples of languages that

don’t use

+

for string concatenation).

JavaScript determines whether to attempt addition or string concatenation by the

types of operands. Both addition and concatenation are evaluated from left to right.

JavaScript examines each pair of operands from left to right, and if either operand is a

string, it assumes string concatenation. If both values are numeric, it assumes addi‐

tion. Consider the following two lines:

3

+

5

+

"8"

// evaluates to string "88"

"3"

+

5

+

8

// evaluates to string "358"

In the first case, JavaScript evaluated

(3 + 5)

as addition first. Then it evaluated

(8 +

"8")

as string concatenation. In the second case, it evaluated

("3" + 5)

as concate‐

nation, then

("35" + 8)

as concatenation.

Logical Operators

Whereas the arithmetic operators we’re all familiar with operate on numbers that can

take on an infinite number of values (or at least a very large number of values, as

computers have finite memory), logical operators concern themselves only with

boolean values, which can take on only one of two values: true or false.
In mathematics—and many other programming languages—logical operators operate

only on boolean values and return only boolean values. JavaScript allows you to oper‐

ate on values that are not boolean, and even more surprising, can return values that

aren’t boolean. That is not to say JavaScript’s implementation of logical operators is

somehow wrong or not rigorous: if you use only boolean values, you will get results

that are only boolean values.

88 | 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.