LEARNING JAVASCRIPT - Trang 167

(a string method) instead of

reduce

. (Start by asking yourself why we need to call

trim

after the

reduce

.)

Hopefully the power of

reduce

is dawning on you. Of all the array methods, it’s the

most general and powerful.

Array Methods and Deleted or Never-Defined Elements

One behavior of the

Array

methods that often trips people up is the way they treat

elements that have never been defined or have been deleted.

map

,

filter

, and

reduce

do not invoke the function for elements that have never been assigned or have been

deleted. For example, before ES6, if you tried to be clever and initialize an array this

way, you would be disappointed:

const

arr

=

Array

(

10

).

map

(

function

(

x

) {

return

5

});

arr

would still be an array with 10 elements, all

undefined

. Similarly, if you delete an

element from the middle of an array, and then call

map

, you’ll get an array with a

“hole” in it:

const

arr

=

[

1

,

2

,

3

,

4

,

5

];

delete

arr

[

2

];

arr

.

map

(

x

=>

0

);

// [0, 0, <1 empty slot>, 0, 0]

In practice, this is seldom a problem because you’re normally working with arrays

whose elements have been explicitly set (and unless you explicitly want a gap in an

array, which is rare, you won’t use

delete

on an array), but it’s good to be aware of.

String Joining

Very often, you simply want to join the (string) value of the elements in an array

together with some separator.

Array.prototype.join

takes a single argument, the

separator (which defaults to a comma if you omit it), and returns a string with the

elements joined together (including never-defined and deleted elements, which

become empty strings;

null

and

undefined

also become empty strings):

const

arr

=

[

1

,

null

,

"hello"

,

"world"

,

true

,

undefined

];

delete

arr

[

3

];

arr

.

join

();

// "1,,hello,,true,"

arr

.

join

(

''

);

// "1hellotrue"

arr

.

join

(

' -- '

);

// "1 -- -- hello -- -- true --"

If used cleverly—and combined with string concatenation—

Array.prototype.join

can be used to create things like HTML

<ul>

lists:

const

attributes

=

[

"Nimble"

,

"Perceptive"

,

"Generous"

];

const

html

=

'<ul><li>'

+

attributes

.

join

(

'</li><li>'

)

+

'</li></ul>'

;

// html: "<ul><li>Nimble</li><li>Perceptive</li><li>Generous</li></ul>";

Array Methods and Deleted or Never-Defined Elements | 143

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.