LEARNING JAVASCRIPT - Trang 161

The functions that you pass to

find

and

findIndex

, in addition to receiving each ele‐

ment as their first argument, also receive the index of the current element and the

whole array itself as arguments. This allows you to do things, for example, such as

finding square numbers past a certain index:

const

arr

=

[

1

,

17

,

16

,

5

,

4

,

16

,

10

,

3

,

49

];

arr

.

find

((

x

,

i

)

=>

i

>

2

&&

Number

.

isInteger

(

Math

.

sqrt

(

x

)));

// returns 4

find

and

findIndex

also allow you to specify what to use for the

this

variable during

the function invocation. This can be handy if you want to invoke a function as if it

were a method of an object. Consider the following equivalent techniques for search‐

ing for a

Person

object by ID:

class

Person

{

constructor

(

name

) {

this

.

name

=

name

;

this

.

id

=

Person

.

nextId

++

;

}
}

Person

.

nextId

=

0

;

const

jamie

=

new

Person

(

"Jamie"

),

juliet

=

new

Person

(

"Juliet"

),

peter

=

new

Person

(

"Peter"

),

jay

=

new

Person

(

"Jay"

);

const

arr

=

[

jamie

,

juliet

,

peter

,

jay

];

// option 1: direct comparison of ID:

arr

.

find

(

p

=>

p

.

id

===

juliet

.

id

);

// returns juliet object

// option 2: using "this" arg:

arr

.

find

(

p

=>

p

.

id

===

this

.

id

,

juliet

);

// returns juliet object

You’ll probably find limited use for specifying the

this

value in

find

and

findIndex

,

but it’s a technique that you’ll see later, where it is more useful.
Just as we don’t always care about the index of an element within an array, sometimes

we don’t care about the index or the element itself: we just want to know if it’s there or

isn’t. Obviously we can use one of the preceding functions and check to see if it

returns –

1

or

null

, but JavaScript provides two methods just for this purpose:

some

and

every

.

some

returns

true

if it finds an element that meets the criteria (all it needs is one; it’ll

stop looking after it finds the first one), and

false

otherwise. Example:

const

arr

=

[

5

,

7

,

12

,

15

,

17

];

arr

.

some

(

x

=>

x

%

2

===

0

);

// true; 12 is even

arr

.

some

(

x

=>

Number

.

isInteger

(

Math

.

sqrt

(

x

)));

// false; no squares

Array Searching | 137

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.