기호 :
...
const fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits);
// 출력 : ['Apple', 'Banana', 'Cherry']
console.log(...fruits);
// 출력 : Apple Banana Cherry
console.log()
에 사용했을 경우, 하나의 배열 데이터를 마치 console.log('Apple', 'Banana', 'Cherry');
코드를 사용하여 출력한 결과처럼 나오게 합니다.const fruits = ['Apple', 'Banana', 'Cherry'];
function toObject(a, b, c) { // 객체데이터로 변환해줄 함수입니다.
return {
a: a,
b: b,
c: c
}
}
console.log(toObject(...fruits));
// {a: "Apple", b: "Banana", c: "Cherry"}
'Apple', 'Banana', 'Cherry'
) 매개변수에도 그대로 활용가능합니다. toObject('Apple', 'Banana', 'Cherry')
const fruits = ['Apple', 'Banana', 'Cherry', 'Orange'];
function toObject(a, b, ...c) { // 객체데이터로 변환해줄 함수입니다.
return {
a: a,
b: b,
c: c
}
}
console.log(toObject(...fruits));
// {a: "Apple", b: "Banana", c: Array(2)}
...c
는 나머지 매개변수
라는 의미로 rest parameter
라고 부릅니다.a
에는 Apple
이, b
에는 Banana
가, 나머지 c
에는 남은 items가(Cherry, Orange
) 배열로 한번에 들어갑니다.함수내부에서 객체데이터를 만들 때, 속성의 이름과 변수의 이름이 같다면 축약할 수 있습니다.
function toObject(a, b, ...c) { // 객체데이터로 변환해줄 함수입니다.
return {
a, // a: a,
b, // b: b,
c // c: c
}
}
더 단순하게 만들 수도 있습니다.
const toObject = (a, b, ...c) => ({ a, b, c });
}