Spread 문법
주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때 사용한다.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers); // 6
Rest 문법
파라미터를 배열의 형태로 받아서 사용할 수 있다. 파라미터 개수가 가변적일 때 유용하다.
함수의 매개변수로 사용할 때에만 Rest 문법을 사용한다고 할 수 있다.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4); // 10
Spread 문법을 배열에서 사용하기
배열 합치기
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의 값 : [1, 2, 3]
// arr2의 값 : [1, 2, 3, 4]
Spread 문법을 객체에서 사용하기
let obj1 = { foo: "bar", x: 42 };
let obj2 = { foo: "baz", y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
// 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");
/* console 출력
a one
b two
manyMoreArgs ["three", "four", "five", "six"]
*/
Destructing
구조 분해 할당은 Spread 문법을 이용하여 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정을 말한다.
분해 후 새 변수에 할당
배열
const [a, b, ...rest] = [10, 20, 30, 40, 50];
// a = 10, b = 20, rest = [30, 40, 50]
객체
const { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 };
// a = 10, b = 20, rest = {c: 30, d: 40}
객체에서 구조 분해 할당을 사용할 경우 선언(const, let, var)과 함께 사용하지 않으면 에러가 발생할 수 있다.
유용한 예제 : 함수에서 객체 분해
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); // jdoe is John
유용한 예제 : for of 반복문과 구조 분해
var people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith",
},
age: 35,
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones",
},
age: 25,
},
];
for (var {
name: n,
family: { father: f },
} of people) {
console.log("Name: " + n + ", Father: " + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
'JavaScript > Vanilla' 카테고리의 다른 글
객체의 얕은 복사와 깊은 복사 (0) | 2021.07.24 |
---|---|
Hoisting (0) | 2021.07.24 |
Closure가 어렵다면 내 탓이 아니라 JS 탓이다! (0) | 2021.07.22 |
let / const / var 그리고 scope (0) | 2021.07.18 |
JavaScript의 탄생 배경 (0) | 2021.07.17 |