
Spread 문법인 … 는 대상을 개별 요소로 분리한다. Spread 문법의 대상은 iterable이어야 한다.
function spread(x,y,z){
console.log(x,y,z); // 1 , 2, 3
//[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
console.log(arguments);
}
const arr =[1,2,3,4];
spread(...arr);
const arr1 =[1,2,3];
const arr2 =[4,5,6];
console.log([...arr1, ...arr2]);
const arr3 =[1,2,3];
const arr4 =[4,5,6];
arr3.push(...arr4); // arr4배열을 개별 요소로 분리
console.log(arr3); // [ 1, 2, 3, 4, 5, 6 ]
const arr3= [1,2,3,6];
const arr4= [4,5];
arr3.splice(3,0,...arr4); [1,2,3,4,5,6]
const arr2 =[1,2,3,6];
const copy2 = [...arr2]; // copy by value
arr2.push(8);
console.log(arr2); //[1,2,3,6,8]
console.log(copy2); // [1,2,3,6]
// 객체 병합
const merged ={...{x:1,y:2}, ...{z:3}};
console.log(merged); // { x: 1, y: 2, z: 3 }
//객체 특정 프로퍼티 변경
const changed ={...{x:1,y:2}, y:100};
console.log(changed); // { x: 1, y: 100 }
// 객체 프로퍼티 추가
const added ={...{x:1,y:2}, z:3};
console.log(added); // { x: 1, y: 2, z: 3 }
함수의 매개변수 이름 앞에 Spread 문법을 붙여서 정의한 매개변수로 함수에 전달된 인수들을 배열로 전달 받는다.
function restParameter( ...rest, param1, param2) { }
restParameter(1, 2, 3, 4, 5);
// SyntaxError: Rest parameter must be last formal parameter
function bar(x, ...rest) {}
console.log(bar.length); // 매개변수 갯수 :1
function sum(...args){
return args.reduce((pre,cur)=> pre +cur,0);
}
console.log(sum(1,2,3,4,5)); // 15