LEARNING JAVASCRIPT - Trang 95

Additional for Loop Patterns

By using the comma operator (which we’ll learn more about in

Chapter 5

), we can

combine multiple assignments and final expressions. For example, here’s a

for

loop

to print the first eight Fibonacci numbers:

for

(

let

temp

,

i

=

0

,

j

=

1

;

j

<

30

;

temp

=

i

,

i

=

j

,

j

=

i

+

temp

)

console

.

log

(

j

);

In this example, we’re declaring multiple variables (

temp

,

i

, and

j

), and we’re modify‐

ing each of them in the final expression. Just as we can do more with a

for

loop by

using the comma operator, we can use nothing at all to create an infinite loop:

for

(;;)

console

.

log

(

"I will repeat forever!"

);

In this

for

loop, the condition will simply evaluate to

undefined

, which is falsy,

meaning the loop will never have cause to exit.
While the most common use of

for

loops is to increment or decrement integer indi‐

ces, that is not a requirement: any expression will work. Here are some examples:

let

s

=

'3'

;

// string containing a number

for

(;

s

.

length

<

10

;

s

=

' '

+

s

);

// zero pad string; note that we must

// include a semicolon to terminate

// this for loop!

for

(

let

x

=

0.2

;

x

<

3.0

;

x

+=

0.2

)

// increment using noninteger

console

.

log

(

x

);

for

(;

!

player

.

isBroke

;)

// use an object property as conditional

console

.

log

(

"Still playing!"

);

Note that a

for

loop can always be written as a

while

loop. In other words:

for([initialization]; [condition]; [final-expression])
statement

is equivalent to:

[initialization]
while([condition]) {
statement
[final-expression]
}

However, the fact that you can write a

for

loop as a

while

loop doesn’t mean you

should. The advantage of the

for

loop is that all of the loop control information is

right there on the first line, making it very clear what’s happening. Also, with a

for

loop, initializing variables with

let

confines them to the body of the

for

loop (we’ll

learn more about this in

Chapter 7

); if you convert such a

for

statement to a

while

statement, the control variable(s) will, by necessity, be available outside of the

for

loop body.

Control Flow Statements in JavaScript | 71

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.