LEARNING JAVASCRIPT - Trang 99

Note that, in this example, we chose to repeat the same action for 11 and 13: omitting

the newline is clearest when cases have single statements and no fall-through

execution.

switch

statements are extremely handy when you want to take many different paths

based on a single expression. That said, you will find yourself using them less once

you learn about dynamic dispatch in

Chapter 9

.

for...in loop

The

for...in

loop is designed to loop over the property keys of an object. The syntax

is:

for(variable in object)
statement

Here is an example of its use:

const

player

=

{

name

:

'Thomas'

,

rank

:

'Midshipman'

,

age

:

25

};

for

(

let

prop

in

player

) {

if

(

!

player

.

hasOwnProperty

(

prop

))

continue

;

// see explanation below

console

.

log

(

prop

+

': '

+

player

[

prop

]);

}

Don’t worry if this seems confusing now; we’ll learn more about this example in

Chapter 9

. In particular, the call to

player.hasOwnProperty

is not required, but its

omission is a common source of errors, which will be covered in

Chapter 9

. For now,

all you need to understand is that this is a type of looping control flow statement.

for...of loop

New in ES6, the

for...of

operator provides yet another way to loop over the ele‐

ments in a collection. Its syntax is:

for(variable of object)
statement

The

for...of

loop can be used on arrays, but more generically, on any object that is

iterable (see

Chapter 9

). Here is an example of its use for looping over the contents of

an array:

const

hand

=

[

randFace

(),

randFace

(),

randFace

()];

for

(

let

face

of

hand

)

console.log(

`You rolled...

${

face

}

!`

);

for...of

is a great choice when you need to loop over an array, but don’t need to

know the index number of each element. If you need to know the indexes, use a regu‐

lar

for

loop:

Control Flow Statements in JavaScript | 75

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.