LEARNING JAVASCRIPT - Trang 123

let

[

x

,

y

]

=

arr

;

x

;

// 1

y

;

// 2

z

;

// error: z hasn't been defined

In this example,

x

is assigned the value of the first element in the array, and

y

is

assigned the value of the second element; all elements past that are discarded. It’s pos‐

sible to take all the remaining elements and put those in a new array with the spread

operator (

...

), which we’ll cover in

Chapter 6

:

const

arr

=

[

1

,

2

,

3

,

4

,

5

];

let

[

x

,

y

,

...

rest

]

=

arr

;

x

;

// 1

y

;

// 2

rest

;

// [3, 4, 5]

In this example,

x

and

y

receive the first two elements, and the variable

rest

receives

the rest (you don’t have to name the variable

rest

; you can use whatever name you

want). Array destructuring makes it easy to swap the values of variables (something

that previously required a temporary variable):

let

a

=

5

,

b

=

10

;

[

a

,

b

]

=

[

b

,

a

];

a

;

// 10

b

;

// 5

Array destructuring doesn’t only work on arrays; it works on any

iterable object (which we’ll cover in

Chapter 9

).

In these simple examples, it would have been easier to simply assign the variables

directly instead of using destructuring. Where destructuring comes in handy is when

you get an object or array from elsewhere, and can easily pick out certain elements.

We’ll see this used to great effect in

Chapter 6

.

Object and Array Operators

Objects, arrays, and functions have a collection of special operators. Some we have

already seen (such as the member access and computed member access operator),

and the rest will be covered in Chapters

6

,

8

, and

9

. For completeness, they are sum‐

marized in

Table 5-10

.

Object and Array Operators | 99

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.