LEARNING JAVASCRIPT - Trang 89

A

for

loop consists of three parts: the initializer (

roll = 0

), the condition (

roll <

3

), and the

final expression (

roll++

). It’s nothing that can’t be constructed with a

while

loop, but it conveniently puts all the loop information in one place. Here’s how

it looks in JavaScript:

const

hand

=

[];

for

(

let

roll

=

0

;

roll

<

3

;

roll

++

) {

hand

.

push

(

randFace

());

}

Programmers have a tendency to count from 0, which is why we start at roll 0 and

stop at roll 2.

It has become a convention to use the variable i (shorthand for

“index”) in a for loop, no matter what you’re counting, though you

can use whatever variable name you wish. I chose roll here to be

clear that we’re counting the number of rolls, but I had to catch

myself: when I first wrote out this example, I used i out of habit!

if Statement

We’re almost there! We’ve placed our bets and rolled our hand; all that’s left is to col‐

lect any winnings. We have three random faces in the

hand

array, so we’ll use another

for

loop to see if any of them are winners. To do that, we’ll use an

if

statement (this

time without an

else

clause). Our final flowchart is shown in

Figure 4-6

.

Notice the difference between an

if...else

statement and an

if

statement: only one

of the

if

statement’s branches lead to an action, whereas both of the

if...else

state‐

ment’s do. We translate this into code for the final piece of the puzzle:

let

winnings

=

0

;

for

(

let

die

=

0

;

die

<

hand

.

length

;

die

++

) {

let

face

=

hand

[

die

];

if

(

bets

[

face

]

>

0

)

winnings

=

winnings

+

bets

[

face

];

}

funds

=

funds

+

winnings

;

Note that, instead of counting to 3 in the

for

loop, we count to

hand.length

(which

happens to be 3). The goal of this part of the program is to calculate the winnings for

any hand. While the rules of the game call for a hand of three dice, the rules could

change…or perhaps more dice are given as a bonus, or fewer dice are given as a pen‐

alty. The point is, it costs us very little to make this code more generic. If we change

the rules to allow more or fewer dice in a hand, we don’t have to worry about chang‐

ing this code: it will do the correct thing no matter how many dice there are in the

hand.

A Control Flow Primer | 65

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.