| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
- django ORM
- CSS
- es6
- 장고
- web
- 파이썬
- react
- DRF
- 알고리즘
- Baekjoon
- MAC
- javascript
- API
- Git
- django widget
- PYTHON
- AWS
- 파이썬 알고리즘
- Django
- 알고리즘 문제
- form
- 알고리즘 풀이
- java
- Algorithm
- HTML
- 백준
- django rest framework
- 알고리즘 연습
- js
- c++
- Today
- Total
수학과의 좌충우돌 프로그래밍
[ES6] Destructuring 본문
Destructuring 의 뜻은 비구조화 입니다.
Destructuring 는 object 나 array, 그 외의 여러 요소들 안의 변수를 바깥으로 꺼내서 사용하는 것을 의미합니다.
여러 요소들에 대한 Destructuring 을 알아보도록 하겠습니다.
Object Destructuring
우선 Object Destructuring 입니다.
Destructuring 을 사용하기 전의 코드를 보도록 하겠습니다.
settings 안에 여러 설정 중에서 follow 에 대한 값을 확인하기 위해서는 다음과 같이 하나씩 순차적으로 타고 들어가야 했습니다.
const settings = {
notifications: {
follow: true,
alerts: true
},
color: {
theme: "dark"
}
};
if (settings.notifications.follow){
console.log("follow 중입니다.");
} else {
console.log("follow 중이 아닙니다.");
}
여기에 Destructuring 를 적용하면 아래와 같이 작성할 수 있습니다.
settings 안에 있는 notifications 안으로 접근해서 follow 만 가져온다.
큰 오브젝트에서 특정 변수나 그 안에 속한 작은 오브젝트에 접근할 수 있도록 해준다.
결과를 확인해보면 notifications 은 정의 되어있지 않은데 이는 단순히 follow 로 접근하기 위한 것이기 변수로 선언한 것이 아니기 때문입니다.
const {
notifications: { follow },
color
} = settings;
console.log(follow); // true
console.log(color); // { theme: 'dark' }
console.log(notifications); // ReferenceError: notifications is not defined
만일 기존 object 데이터에 follow 가 없다면 어떻게 될까요?
정의되지 않았다고 나옵니다.
const settings = {
notifications: {
alerts: true
},
color: {
theme: "dark"
}
};
const {
notifications: { follow },
} = settings;
console.log(follow);
// undefined
이를 해결하기 위해 default value 를 넣어줄 수 있습니다.
const {
notifications: { follow = false },
color
} = settings;
console.log(follow);
// false
이번에는 notifications 이 통째로 없다면 어떻게 될 지 생각해봅시다.
notifications 이 정의되지 않았기 때문에 오류가 발생합니다.
const settings = {
color: {
theme: "dark"
}
};
const {
notifications: { follow = false },
color
} = settings;
console.log(follow);
// TypeError: Cannot destructure property `follow` of 'undefined' or 'null'.
이 경우 아래와 같이 notifications 에도 default value 를 지정해 줄 수 있습니다.
현재 default value 는 빈 오브젝트입니다.
const {
notifications: { follow = false } = {},
color
} = settings;
console.log(follow);
// false
다음과 같은 형식을 one-line-statement 라고 합니다.
여러 분기문을 한 줄로 쉽게 표현해줄 수 있죠.
const { notifications: { follow = false } = {} } = settings;
Array Destructuring
array destructuring 도 비슷한 개념을 array 에 적용한 것으로서 가져온 정보를 조작하지 않을 때 쓰기 편합니다.
아래와 같이 과일 array 가 있고 이 중에서 앞의 3개의 과일을 가져오기 위해서는 다음과 같이 할 수 있습니다.
const fruits = ["apple", "banana", "melon", "strawberry"]
const f1 = fruits[0];
const f2 = fruits[1];
const f3 = fruits[2];
console.log(f1, f2, f3);
// apple banana melon
이에 destructuring 를 적용해보겠습니다.
array 에는 object 처럼 key 값은 존재하지 않고 포지션값만 존재하기 때문에 따로 key 값을 기재하지 않고 { } 대신 [ ] 을 사용합니다.
const fruits = ["apple", "banana", "melon", "strawberry"]
const [f1, f2, f3] = fruits;
console.log(f1, f2, f3);
// apple banana melon
이 역시 default value 를 지정해줄 수 있습니다.
const fruits = ["apple", "banana"]
const [f1, f2, f3 = "melon"] = fruits;
console.log(f1, f2, f3);
// apple banana melon
Renaming
말 그대로 변수의 이름을 바꿔주는 것을 말합니다.
destructuring 을 사용하지 않았을 경우에는 다음과 같이 변경이 가능합니다.
const settings = {
color: {
theme: "dark"
}
};
const changeName = settings.color.theme || "light";
console.log(changeName);
// dark
destructuring 을 사용하는 경우에도 쉽게 가능합니다.
기존의 변수명 뒤에 : 와 새로운 변수명을 기재해주면 됩니다.
const {
color: {theme: changeName = "light" }
} = settings;
console.log(changeName);
// dark
만일 changeName 이 기존에 존재하던 변수였다면 어떻게 해야할까요?
1번과 2번은 정의되있는 변수명에 대해 재정의 하는 것이기 때문에 오류가 발생하고 3번도 문법적인 오류가 발생합니다.
let changeName = "light";
// 1번
const {
color: {theme: changeName = "light" }
} = settings;
// 2번
let {
color: {theme: changeName = "light" }
} = settings;
// 3번
{
color: {theme: changeName = "light" }
} = settings;
이 경우에는 문장 전체를 ( ) 로 감싸주면 해결됩니다.
let changeName = "light";
({
color: {theme: changeName = "light" }
} = settings);
console.log(changeName);
Function Destructuring
여러 설정 object 를 받아 이를 저장하는 saveSettings 함수를 만들어봅시다.
물론 저장하는 기능을 구현하진 않고 결과를 출력 해보도록 하죠.
이 경우에 단점은 각 값에 접근하기 위해서는 꼭 settings. 이라는 수식어가 하나씩 붙는다는 것이죠.
function saveSettings(settings){
console.log(`follow: ${settings.follow}`);
}
saveSettings({
follow: true,
alerts: true
})
// follow: true
여기서도 함수의 파라미터에 Destructuring 을 사용하면 해결할 수 있습니다.
default value 도 기존과 동일한 방법으로 적용가능합니다.
function saveSettings({follow, alerts, color = "light" }){
console.log(`follow: ${follow}`);
}
saveSettings({
follow: true,
alerts: true
})
// follow: true
Value Shorthands
기존의 두 값을 settings 의 key값들에 넣어주는 간단한 예제입니다.
settings object 안을 보면 follow 라는 key값과 변수명이 중복됩니다.
이ㄴ alerts 도 마찬가지이고요.
const follow = true;
const alerts = true;
const settings = {
follow: follow,
alerts: alerts
}
console.log(settings);
// { follow: true, alerts: true }
다음과 같이 key값과 변수명을 똑같이 사용하는게 더 흔한 일입니다.
그렇기 때문에 ES6 에서도 이를 효율적으로 바꿀 수 있는 방법을 마련했습니다.
아래와 같이 한 번만 적어주면 위와 같은 결과가 나오는 것을 확인할 수 있습니다.
const follow = true;
const alerts = true;
const settings = {
follow,
alerts
}
console.log(settings);
// { follow: true, alerts: true }
Swapping and Skipping
둘 모두 array Destructuring 을 사용하는 방법입니다.
먼저 swapping 부터 알아봅시다.
swapping 은 array Destructuring 을 이용해서 변수의 값을 바꿔주는 방법입니다.
4번째 줄 우항에 있는 apple 과 banana 는 각각 "banana" 와 "apple" 로 변하고 각각에 맞는 변수로 다시 대입되는 원리입니다.
let apple = "banana";
let banana = "apple";
[banana, apple] = [apple, banana];
console.log(apple, banana);
// apple banana
다음으로는 skipping 입니다.
이는 array 에서 중간의 값들만 필요할 때 사용하는 방법입니다.
필요없는 값들은 , 를 통해서 자리를 표시해주고 필요한 값들만 받아주도록 합니다.
const fruits = ["apple", "banana", "melon", "strawberry"];
const [, banana, , strawberry] = fruits;
console.log(banana, strawberry);
// banana strawberry
'웹프로그래밍 > ES6' 카테고리의 다른 글
| [ES6] Loop 에 대해서 알아보자 forEach, for of (0) | 2020.01.02 |
|---|---|
| [ES6] Spread and Rest (0) | 2020.01.02 |
| [ES6] Array Method (0) | 2019.12.31 |
| [ES6] Template Literal 과 String Method (0) | 2019.12.31 |
| [ES6] Arrow Function 과 Default Value (0) | 2019.12.31 |