spread/rest 문법
spread 문법
- 주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때에 사용한다.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers)
rest 문법
- 파라미터를 배열의 형태로 받아서 사용할 수 있다.
- 파라미터 개수가 가변적일 때 유용하다.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
sum(1,2,3)
sum(1,2,3,4)
배열에서 사용하기
1. 배열 합치기
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
2. 배열 복사
let arr = [1, 2, 3];
let arr2 = [...arr];
arr2.push(4);
객체에서 사용하기
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
함수에서 나머지 파라미터 받아오기
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
분해 후 새 변수에 할당
배열
const [a, b, ...rest] = [10, 20, 30, 40, 50];
객체
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
- 객체에서 구조 분해 할당을 사용하는 경우,
선언(const, let, var)
과 함께 사용하지 않으면 에러가 발생할 수 있다.
구조 분해 할당
- 배열이나 객체의 속성을 분해하여 그 값을 개별 변수에 담을 수 있게 하는 JS 표현식이다.
- 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의한다.
- 객체에서 구조 분해 할당 사용 시, 선언 키워드와 함께 사용하지 않으면 에러가 발생할 수 있다.
- 구조 분해를 통해 선언과 분리하여 변수에 값을 할당할 수 있다.
함수에서 객체 분해
function whois({displayName: displayName, fullName: {firstName: name}}){
console.log(displayName + " is " + name);
}
let user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
whois(user)