LEARNING JAVASCRIPT - Trang 132

The implication of this is that you can call any function with any number of argu‐

ments. If you fail to provide arguments, they will implicitly receive the value

undefined

:

function

f

(

x

) {

return

`in f: x=

${

x

}

`

;

}

f

();

// "in f: x=undefined"

Later in this chapter, we’ll see how to handle the situation where you pass more argu‐

ments than the function defines.

Destructuring Arguments

Just as we can have destructured assignment (see

Chapter 5

), we can have destruc‐

tured arguments (arguments are, after all, very much like variable definition). Con‐

sider destructuring an object into individual variables:

function

getSentence

({

subject

,

verb

,

object

}) {

return

`

${

subject

}

${

verb

}

${

object

}

`

;

}

const

o

=

{

subject

:

"I"

,

verb

:

"love"

,

object

:

"JavaScript"

,

};

getSentence

(

o

);

// "I love JavaScript"

As with destructuring assignment, property names must be identifier strings, and a

variable that doesn’t have a matching property in the incoming object will receive the

value

undefined

.

You can also destructure arrays:

function

getSentence

([

subject

,

verb

,

object

]) {

return

`

${

subject

}

${

verb

}

${

object

}

`

;

}

const

arr

=

[

"I"

,

"love"

,

"JavaScript"

];

getSentence

(

arr

);

// "I love JavaScript"

Finally, you can use the spread operator (

...

) to collect any additional arguments:

function

addPrefix

(

prefix

,

...

words

) {

// we will learn a better way to do this later!

const

prefixedWords

=

[];

for

(

let

i

=

0

;

i

<

words

.

length

;

i

++

) {

prefixedWords

[

i

]

=

prefix

+

words

[

i

];

}

return

prefixedWords

;

108 | Chapter 6: Functions

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.