LEARNING JAVASCRIPT - Trang 102

For example, we might want to remove all prime numbers from

bigArrayOfNumbers

.

We’ll use an array method called

splice

, which can add or remove elements from an

array (see

Chapter 8

). The following will not work as expected:

for

(

let

i

=

0

;

i

<

bigArrayOfNumbers

.

length

;

i

++

) {

if

(

isPrime

(

bigArrayOfNumbers

[

i

]))

bigArrayOfNumbers

.

splice

(

i

,

1

);

}

Because the index is increasing, and we’re removing elements, there’s a possibility that

we might skip over primes (if they are adjacent). We can solve this problem by using

descending indexes:

for

(

let

i

=

bigArrayOfNumbers

.

length

-

1

;

i

>=

0

;

i

--

) {

if

(

isPrime

(

bigArrayOfNumbers

[

i

]))

bigArrayOfNumbers

.

splice

(

i

,

1

);

}

Note carefully the initial and test conditions: we have to start with one less than the

length of the array, because arrays indexes are zero-based. Also, we continue the loop

as long as

i

is greater than or equal to 0; otherwise, this loop won’t cover the first ele‐

ment in the array (which would cause problems if the first element were a prime).

Conclusion

Control flow is really what makes our programs tick. Variables and constants may

contain all the interesting information, but control flow statements allow us to make

useful choices based on that data.
Flowcharts are a useful way to describe control flow visually, and very often it can be

helpful to describe your problem with a high-level flowchart before you start writing

code. At the end of the day, however, flowcharts are not very compact, and code is a

more efficient and (with practice) natural way to express control flow (many attempts

have been made to construct programming languages that were visual only, yet text-

based languages have never been threatened by this usurper).

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