한입 크기로 잘라 먹는 리액트(React.js) 강의 내용을 정리하며 JavaScript의 응용에 대해 알아보자.
🏷️ 구조 분해 할당이라고도 부른다.
let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];
console.log(one, two, three);
👉🏻 이렇게 arr의 반복되는 값을 줄이기 위해 사용한다.
let arr = ["one", "two", "three"];
let [one, two, three] = arr;
👉🏻 동일한 결과가 출력된다.
let [one, two, three] = ["one", "two", "three"]
👉🏻 더 단축도 가능하다.
👉🏻 배열의 선언 분리 비구조화 할당이라고 부른다. (정확한 명칭은 몰라도 된다.)
👉🏻 비구조화해서 여러가지로 할당이 가능하며 순서대로 변수를 할당한다.
let [one, two, three, four = "four"] = ["one", "two", "three"]
👉🏻 기본값을 지정하면 할당을 못 받아도 undefined가 아닌 기본값으로 할당이 된다.
🏷️ Swap에도 활용이 가능하다.
let a = 10;
let b = 20;
let tmp = 0;
tmp = a;
a = b;
b = tmp;
👉🏻 아래 코드로 교체 가능하다.
let a = 10;
let b = 20;
[a, b] = [b, a];
let object = { one : "one", two : "two", three : "three"};
let one = object["one"];
let two = object.two;
let three = object.three;
👉🏻 반복노동을 아래와 같이 줄일 수 있다.
let object = { one : "one", two : "two", three : "three"};
let {one, two, three } = object;
👉🏻 순서가 아닌 key값으로 비구조화 할당이 이루어진다. 따라서 순서에 무관하다.
👉🏻 React에 자주 사용된다.
let object = { one : "one", two : "two", three : "three", name : "myName"};
let {name : myName, one, two, three } = object;
👉🏻 변수명을 바꾸면 이름을 바꿔서도 할당이 가능하다.
👉🏻 배열과 마찬가지로 기본값 적용이 가능하다.
🏷️ 객체를 다루는 또 다른 방식이다.
const cookie = {
base : "cookie",
madeIn : "Korea"
};
const chocochipCookie = {
base : "cookie",
madeIn : "Korea",
toping : "chocochip"
};
const blueberryCookie = {
base : "cookie",
madeIn : "Korea",
toping : "blueberry"
};
const strawberryCookie = {
base : "cookie",
madeIn : "Korea",
toping : "strawberry"
};
👉🏻 중복된 값을 계속 사용 시 spread 연산자를 사용하면 간단하다.
const cookie = {
base : "cookie",
madeIn : "Korea"
};
const chocochipCookie = {
...cookie,
toping : "chocochip"
};
const blueberryCookie = {
...cookie,
toping : "blueberry"
};
const strawberryCookie = {
...cookie,
toping : "strawberry"
};
👉🏻 ...연산을 spread 연산자라고 부른다.
🏷️ 배열에서도 사용 가능하다.
const noTopingCookies = ["촉촉한쿠키","안촉촉한쿠키"];
const topingCookies = ["바나나쿠키", "블루베리쿠키","딸기쿠키","초코칩쿠키"];
const allCookies = [...noTopingCookies, "함정쿠키", ...topingCookies];
👉🏻 배열을 이어붙일 때 사용 가능하다.
👉🏻 concat과 기능은 동일하지만 ...연산은 중간에 "함정쿠키"처럼 값을 넣을 수 있다는 차이점이 존재한다.