스프레드 문법(전개 구문) 은 주로 배열을 풀어서 요소를 전달하거나, 확장할때 사용합니다
function sum(a, b, c) {
return a + b + c
}
const numbers = [1, 2, 3];
sum(...numbers); // sum의 매개변수 인자로 numbers배열의 요소가 전덜된다
// spread 형태가 아니라면, a로 numbers의 배열값이 그대로 들어가게된다
// a에 배열값 1,2,3 이들어가게되버리고, b , c는 인자가 없기때문에 undefined
sub(numbers); // output : '1,2,3undefinedundefined'
function sum(a, b, c) {
return a + b + c
}
const numbers = [1, 2, 3];
// spread 형태가 아닐경우 아래와 같이 `apply`를 사용하여 인수를 전달 하였다
sum.apply(null, numbers);
let color = ['red', 'blue', 'pink'];
let color2 = [...color, 'pink', 'white'];
// srepad 뭄법은 기존 배열을 변경하지 않으며 (immutable), 해당하는 위체에 배열의 요소가 들어가 합쳐지게 된다
console.og(color2); // ['red', 'blue', 'pink', black', 'white'];
let obj = { a: 1, b: 2 }
let obj2 = {...obj, b: 3, c: 4, d: 5}
// 객체의 경우 같은 key값이 존재하면 값이 덮어씌워진다
console.log(obj2); // {a: 1, b: 3, c: 4, d: 5}
let number = [1,2,3];
let number2 = [...number];
// 배열을 합칠 때와 마찬가지로, 빈배열에 spread 연산자를 통해 배열을 가져와 넣는 것이기 때문에 마치 배열을 복사하는 형태가된다 ( [Array.prototype.slice()](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) 와 비슷한 기능 )
console.log(number2); // [1,2,3]
let obj = { a: 1, b: 2 }
let obj2 = { ...obj }
console.log(obj2); // { a: 1, b: 2 }
함수의 매개변수(Parameter)의 이자를 받을때 정해지지 않은 수의 매개 변수를 배열로 받을 수 있습니다
function sum(...args) {
let total = 0;
console.log(args); // [1, 2, 3]
for (const arg of args) {
total += arg;
}
return total;
}
// ...ars 에는 인자로 받은 1,2,3 이 배열로 들어가게 된다
console.log(sum(1,2,3)); // output : 6
function sum(a, b, ...args) {
console.log(args); // [3, 4]
// arguments 사용 시 전달된 모든 인자를 (유사)배열로 받을 수 있다
// 화살표 함수에서는 사용할 수 없다
console.log(arguments); // Arguments[] 의 유사배열객체 형태
const array = Array.prototype.slice.call(arguments);
console.log(array); // [1, 2, 3, 4];
}
sum(1, 2, 3, 4);