Javascript ES6 문법 공부 6

김동현·2022년 6월 13일
0

ES6 문법공부

목록 보기
6/7

Javascript의 Destructuring 기능을 공부했다.

1. object destructuring

destructuring은 Object 나 Array, 그 외 요소들 안의 변수를
바깥으로 끄집어 내서 사용할 수 있도록 하는 것.
default 값을 설정해서 변수를 선언 가능!

const settings = {
    notificattions: {
        follow: true,
        alerts: true,
        unfollow: false,
    },
    color: {
        theme: 'dark',
    },
};

const {
    notificattions: { follow = false },
    color: { theme },
} = settings;

console.log(follow);
console.log(theme);
* rename
const {chosen_color : chosenColor = "light"} = settings;

기존의 object의 key값을 가져오면서 콜론(:)을 추가 해주고, 뒤에 변수명을 적어주면
새로 작성한 변수명으로 선언가능하다.

let chosenColor = "blue";
({chosen_color : chosenColor = "light"} = settings);

다음과 같이 하면 let으로 선언된 변수명으로 rename기능을 사용할 수 있다.

2. array destructuring

array의 요소를 간단하게 변수로서 할당 가능하다.
당연하게 default 값도 설정 가능하다.

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

const [mon, tue, wed] = days;

3. function destructuring

여러개의 arguments를 Object로 선언해 destructuring 기능 이용가능!

function saveSettings({ follow, alert, color: { theme } }) {
    console.log(settings);
}

saveSettings({
    notifications: {
        follow: true,
        alert: true,
        mkt: false,
    },
    color: {
        theme: 'blue',
    },
});

4. others

object에서 key값과 변수명이 같을 경우 생략이 가능하다.

const follow = checkFollow();

const settings = {
    notifications : {
        follow,
    }
}
* variable swapping

변수의 값을 교체한다.

let mon = 'Sat';
let sat = 'Mon';

console.log(mon, sat);

[mon, sat] = [sat, mon];

console.log(mon, sat);
* skipping variable

값을 생략하고 변수를 만든다!

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

const [, , , , fri, sat] = days;

console.log(fri, sat);
profile
프론트엔드 개발자...이고 싶은 사람

0개의 댓글