주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때에 사용합니다.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers) // 질문: 어떤 값을 리턴하나요? 답: 6
파라미터를 배열의 형태로 받아서 사용할 수 있습니다. 파라미터 개수가 가변적일 때 유용합니다.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
sum(1,2,3) // 질문: 어떤 값을 리턴하나요? 답: 6
sum(1,2,3,4) // 질문: 어떤 값을 리턴하나요? 답: 10
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
// 질문: lyrics의 값은 무엇인가요?
// 답: ['head', 'shoulders', 'knees', 'and', 'toes']
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // 참고: spread 문법은 기존 배열을 변경하지 않으므로(immutable), arr1의 값을 바꾸려면 새롭게 할당해야 합니다.
// 질문: arr1의 값은 무엇인가요? 답: [0, 1, 2, 3, 4, 5]
let arr = [1, 2, 3];
let arr2 = [...arr]; // arr.slice() 와 유사
arr2.push(4); // 참고: spread 문법은 기존 배열을 변경하지 않으므로(immutable), arr2를 수정한다고, arr이 바뀌지 않습니다.
// 질문: arr와 arr2의 값은 각각 무엇인가요?
// 답: arr = [1, 2, 3] 답: arr2 = [1, 2, 3, 4]
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
// 질문: clonedObj와 mergedObj의 값은 각각 무엇인가요?
// 답: clonedObj = {foo: 'bar', x: 42}
// mergedObj = {foo: 'baz', x: 42, y: 13}
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
/* 질문: 콘솔은 순서대로 어떻게 찍힐까요?
답:
a one
b two
manyMoreArgs (4) ['three', 'four', 'five', 'six'] */
구조 분해 할당은 Spread 문법을 이용하여 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정을 말합니다.
배열
const [a, b, ...rest] = [10, 20, 30, 40, 50];
/* 질문: a, b, rest는 각각 어떤 값인가요?
답: a = 10, b = 20, rest = [30, 40, 50]
객체
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
/* 질문: a, b, rest는 각각 어떤 값인가요?
답: a = 10, b = 20, rest = {c: 30, d: 40}
유용한 예제: 함수에서 객체 분해
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) // 질문: 콘솔에서 어떻게 출력될까요? 답: jode is John
알게 된 것들:
호이스팅이란? 함수 안에 있는 선언들을 모두 끌어올려서 해당 함수 유효 범위의 최상단에 선언하는 것을 말한다.
복사 3가지
1. 단순 객체 복사(주소 참조)
2. 얕은 복사 : 다른 주소이지만, 참조 요소는 복사되지 않음 ex. Object.assign
3. 깊은 복사 : 전부 온전하게 다른 주소
// 1. 단순 객체 복사(주소 참조)
let a = [1, 2, 3, 4]
let b = a;
b = [1, 2, 3, 4]
b[2] = 100;
b = [1, 2, 100, 4]
a = [1, 2, 100, 4]
// 2. 얕은 복사
const target = {a: 1, b: 2 };
const source = {b: 4, c: 5 };
const returnedTarget = Object.assign
target = {a: 1, b: 4, c: 5}
returnedTarget = {a: 1, b: 4, c: 5}
returnedTarget.a = "hi"
returnedTarget = {a: 'hi', b: 4, c: 5}
target = {a: 'hi', b: 4, c: 5}
/* 3. 깊은 복사
방법1. JSON.strigify : 객체를 스트링 포맷으로 변환
방법2. 반복문 활용 복사
방법3. lodash 라이브러리의 cloneDeep() 메소드 활용 */
(책 추천)모던 자바스크립트 Deep Dive