구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.
쉽게 말하면, 객체 속성들을 할당할 때 구조를 분해하여 개별 변수에 담을 수 있도록 하는 표현식이다.
배열
- 변수 할당 후 선언하기
기존 문법
var foo = ["one", "two", "three"];
var red = foo[0]
var yellow = foo[1]
var green = foo[2]
console.log(red); // "one"
console.log(yellow) // "two"
console.log(green) // "three"
결과값
one
two
three
기존에는 배열 하나씩 일일이 할당해 줬어야 했다.
새로운 문법
var foo = ["one", "two", "three"];
var [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow) // "two"
console.log(three) // "three"
결과값
one
two
three
분리해서 바로 할당이 가능해졌다.
객체
- 변수 할당 후 선언하기
기존 문법
// ES5 문법
const car = {
year: '2020',
color: 'black',
type : 'SUV'
};
let car_year = car.yaer;
let car_color = car.color;
let car_type = car.type;
console.log(car_year);
console.log(car_color);
console.log(car_type);
결과값
2020
black
SUV
기존문법은 코드가 길었다. 이것을 보완한 코드가 아래 코드이다.
새로운 문법
// ES6 문법
const car = {
year: '2020',
color: 'black',
type : 'SUV'
};
let {year, color, type} = car // 기존 이름의 변수에 할당하기
console.log(year);
console.log(color);
console.log(type);
///////////////////////////
let {year: car_year, color: car_color, type: car_type} = car // 새로운 이름의 변수에 할당하기
console.log(car_year);
console.log(car_color);
console.log(car_type);
let {year, color, type} = car
위의 표현식을 사용하면 기존 이름의 변수에 할당이 가능하다.
하지만 주의할 점은 car의 key값과 동일해야만 한다.
새로운 이름의 변수에 할당하기 위해서는
let {year: car_year, color: car_color, type: car_type} = car 이렇게 표현해야 한다. year, color, type은 car의 key 값이고 그 다음에 나오는 변수들이(car_year, car_color, car_type) 새로운 이름에 할당되는 변수이다.
유용하게 쓸것같은 관련 표현식
- swap
var a = true;
var b = false;
[a,b] = [b,a]
console.log(a + " , " + b) // false , true
[a,b] = [b,a]
- 배열에 나머지 할당하기
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
...b를 사용하면 나머지 값만 저장 가능
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }
이런식으로도 가능
reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
'개발 > JavaScript' 카테고리의 다른 글
[JS] 전개구문(Spread Syntax) - ...(three dots) (0) | 2022.02.25 |
---|---|
Javascript로 작성하는 선언적 프로그래밍(Declarative Programming) (0) | 2022.02.25 |
JS, CSS, HTML로 만든 슬라이드 (0) | 2021.11.10 |
[Javascript] 변수(const, var, let)와 전역공간 (0) | 2021.07.23 |
[Javascript] 참조 타입 (Object Type) (0) | 2021.05.24 |