LEARNING JAVASCRIPT - Trang 157

Some languages, like Ruby, have conventions that make it easy to

tell if a method modifies something in place or returns a copy. For

example, in Ruby, if you have a string str, and you call str.down
case

, it will return a lowercased version, but str will remain

unchanged. On the other hand, if you call str.downcase!, it will

modify str in place. The fact that the standard libraries in Java‐

Script offer no clue about which methods return a copy and which

modify in place is, in my opinion, one of the language’s shortcom‐

ings, requiring unnecessary memorization.

Adding or Removing Single Elements at the Beginning or End

When we refer to the beginning (or front) of an array, we’re referring to the first ele‐

ment (element 0). Likewise, the end (or back) of an array is the largest element (if our

array is

arr

, element

arr.length-1

).

push

and

pop

add and remove, respectively, ele‐

ments to the end of the array (in place).

shift

and

unshift

remove and add, respec‐

tively, elements to the beginning of the array (in place).

The names of these methods come from computer science termi‐

nology. push and pop are actions on a stack, where the important

elements were the most recent ones added. shift and unshift

treat the array like a queue, where the important elements are the

oldest ones added.

push

and

unshift

return the new length of the array after the new element has been

added, and

pop

and

shift

return the element that was removed. Here are examples of

these methods in action:

const

arr

=

[

"b"

,

"c"

,

"d"

];

arr

.

push

(

"e"

);

// returns 4; arr is now ["b", "c", "d", "e"]

arr

.

pop

();

// returns "e"; arr is now ["b", "c", "d"]

arr

.

unshift

(

"a"

);

// returns 4; arr is now ["a", "b", "c", "d"]

arr

.

shift

();

// returns "a"; arr is now ["b", "c", "d"]

Adding Multiple Elements at the End

The

concat

method adds multiple elements to the array and returns a copy. If you

pass

concat

arrays, it will break apart those arrays and add their elements to the orig‐

inal array. Examples:

const

arr

=

[

1

,

2

,

3

];

arr

.

concat

(

4

,

5

,

6

);

// returns [1, 2, 3, 4, 5, 6]; arr unmodified

arr

.

concat

([

4

,

5

,

6

]);

// returns [1, 2, 3, 4, 5, 6]; arr unmodified

arr

.

concat

([

4

,

5

],

6

);

// returns [1, 2, 3, 4, 5, 6]; arr unmodified

arr

.

concat

([

4

, [

5

,

6

]]);

// returns [1, 2, 3, 4, [5, 6]]; arr unmodified

Array Content Manipulation | 133

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.