배열데이터가 쉼표로 구분된 각각의 아이템으로 전개된다.
const fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits); // ['Apple', 'Banana', 'Cherry']
console.log(...fruits); // 'Apple', 'Banana', 'Cherry'
매개변수로 값을 받아 key:value 형태로 객체를 리턴하는 함수가 있다.
const fruits = ['Apple', 'Banana', 'Cherry'];
function toObject(a, b, c) { // a, b, c를 매개변수로 받아 key의 value로 할당
return {
a: a,
b: b,
c: c
}
}
fruits 배열의 값을 사용하여 객체를 생성하고 싶다면
아래와같이 작성해주어야 한다.
const fruitsObj = toObject(fruits[0], fruits[1], fruits[2]);
console.log(fruitsObj);
//{
// a: 'Apple',
// b: 'Banana',
// c: 'Cherry'
//}
인수의 개수대로 작성해주어야해서 몹시 불편하다.
But, 전개 연산자를 사용하면
const fruitsObj = toObject(...fruits);
console.log(fruitsObj);
//{
// a: 'Apple',
// b: 'Banana',
// c: 'Cherry'
//}
함수에 실제로 전달되는 인수를 제외한 나머지 모든 인수를 받는 매개변수.
...로 시작된다.
const fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Blueberry'];
function toObject(a, b, ...c) { // a, b, c를 매개변수로 받아 key의 value로 할당
return {
a: a,
b: b,
c: c
}
}
const fruitsObj = toObject(...fruits);
console.log(fruitsObj);
//{
// a: 'Apple',
// b: 'Banana',
// c: ['Cherry', 'Orange', 'Blueberry']
//}
function toObject(a, b, ...c) {
return {
a: a,
b: b,
c: c
}
}
// 위 함수는
const toObject = (a, b, ...c) => ({ a, b, c })
// 위와같이 축약 가능하다.