LEARNING JAVASCRIPT - Trang 88

Note how this differs from the

while

loop: the decision comes at the end, not the

beginning.

do...while

loops are for when you know you always want to execute the

body of the loop at least once (if the condition in a

while

loop starts off as falsy, it

won’t even run once). Now in JavaScript:

let

remaining

=

totalBet

;

do

{

let

bet

=

rand

(

1

,

remaining

);

let

face

=

randFace

();

bets

[

face

]

=

bets

[

face

]

+

bet

;

remaining

=

remaining

-

bet

;

}

while

(

remaining

>

0

);

for Loop

Thomas has now placed all his bets! Time to roll the dice.
The

for

loop is extremely flexible (it can even replace a

while

or

do...while

loop),

but it’s best suited for those times when you need to do things a fixed number of

times (especially when you need to know which step you’re on), which makes it ideal

for rolling a fixed number of dice (three, in this case). Let’s start with our “roll dice”

flowchart, shown in

Figure 4-5

.

Figure 4-5. Crown and Anchor simulation: roll dice flowchart

64 | Chapter 4: Control Flow

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.