LEARNING JAVASCRIPT - Trang 85

At a glance, it looks like the body of the

while

loop is executing two statements (two

steps forward and one step back), but because there’s no block statement here, Java‐

Script interprets this as:

while

(

funds

>

1

&&

funds

<

100

)

funds

=

funds

+

2

;

// while loop body

funds

=

funds

-

1

;

// after while loop

I side with those who say that omitting the block statement for single-line bodies is

acceptable, but of course you should always be responsible with indentation to make

your meaning clear. Also, if you’re working on a team or an open source project, you

should adhere to any style guides agreed upon by the team, regardless of your per‐

sonal preferences.
While there is disagreement on the issue of using blocks for single-statement bodies,

one syntactically valid choice is nearly universally reviled: mixing blocks and single

statements in the same

if

statement:

// don't do this

if

(

funds

>

1

) {

console

.

log

(

"There's money left!"

);

console

.

log

(

"That means keep playing!"

);

}

else

console

.

log

(

"I'm broke! Time to quit."

);

// or this

if

(

funds

>

1

)

console

.

log

(

"There's money left! Keep playing!"

);

else

{

console

.

log

(

"I'm broke"

!

);

console

.

log

(

"Time to quit."

)

}

Helper Functions

To follow along with the examples in this chapter, we’ll need two helper functions. We

haven’t learned about functions yet (or pseudorandom number generation), but we

will in upcoming chapters. For now, copy these two helper functions verbatim:

// returns a random integer in the range [m, n] (inclusive)

function

rand

(

m

,

n

) {

return

m

+

Math

.

floor

((

n

-

m

+

1

)

*

Math

.

random

());

}

// randomly returns a string representing one of the six
// Crown and Anchor faces

function

randFace

() {

return

[

"crown"

,

"anchor"

,

"heart"

,

"spade"

,

"club"

,

"diamond"

]

[

rand

(

0

,

5

)];

}

A Control Flow Primer | 61

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.