LEARNING JAVASCRIPT - Trang 96

switch Statements

Where

if...else

statements allow you to take one of two paths,

switch

statements

allow you to take multiple paths based on a single condition. It follows, then, that the

condition must be something more varied than a truthy/falsy value: for a

switch

statement, the condition is an expression that evaluates to a value. The syntax of a

switch

statement is:

switch

(

expression

) {

case

value1

:

// executed when the result of expression matches value1

[

break

;]

case

value2

:

// executed when the result of expression matches value2

[

break

;]

...

case

valueN

:

// executed when the result of expression matches valueN

[

break

;]

default

:

// executed when none of the values match the value of expression

[

break

;]

}

JavaScript will evaluate

expression

, pick the first

case

that matches, and then exe‐

cute statements until it sees a

break

,

return

,

continue

,

throw

or the end of the

switch

statement (we will learn about

return

,

continue

, and

throw

later). If that

sounds complex to you, you’re not alone: because of the nuances of the

switch

state‐

ment, it’s received a lot of criticism as being a common source of programmer error.

Often, beginning programmers are discouraged from using it at all. I feel that the

switch

statement is very useful in the right situation: it’s a good tool to have in your

toolbox, but like any tool, you should exercise caution, and use it when appropriate.
We’ll start with a very straightforward example of a

switch

statement. If our fictional

sailor has multiple numbers he’s superstitious about, we can use a

switch

statement

to handle them accordingly:

switch

(

totalBet

) {

case

7

:

totalBet

=

funds

;

break

;

case

11

:

totalBet

=

0

;

break

;

case

13

:

totalBet

=

0

;

break

;

case

21

:

totalBet

=

21

;

72 | 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.