티스토리 뷰
728x90
반응형
개념
[ ] 대괄호를 이용해서 배열이나 객체의 값을 순서대로 할당 받아서 사용할 수 있는 방법
배열의 비 구조화 할당
let arr = ['one', 'two', 'three'];
let one = arr[0];
let two = arr[1];
let three = arr[2];
위의 코드를 비 구조화 할당으로 간략하게 나타내면 다음과 같다.
let [one, two, three, four] = ["one", "two", "three"];
console.log(one, two, three, four); // one two three undefined 출력
또한, 기본값 설정을 하고 싶다면 다음과 같이 사용한다.
let [one, two, three, four='four'] = ['one', 'two', 'three'];
console.log(one, two, three, four); // one two three four 출력
또한, 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 값을 기준으로 할당 하게 된다. 만약 key 값이 아니라 다른 이름의 변수로 사용 하고 싶다면 다음과 같이 표현해주면 된다.
let object = { one: "one", two: "two", three: "three", name: "에스파니아" };
let { one, two, three, name: myname } = object;
console.log(one, two, three, myname); //one two three 에스파니아
또한, 기본값 설정을 하고 싶다면 배열에서와 마찬가지로 = 연산자를 사용하여 다음과 같이 사용한다.
let object = { one: "one", two: "two", three: "three", name: "에스파니아" };
let { one, two, three, name: myname, four = "four" } = object;
console.log(one, two, three, myname, four); //one two three 에스파니아 four
728x90
'JavaScript' 카테고리의 다른 글
| [javascript] 자바스크립트 엔진?? V8은 무엇일까?? (0) | 2022.02.23 |
|---|---|
| [javascript] 싱글 스레드 작업 수행 방식이 어떻게 될까요?? (0) | 2022.02.23 |
| [javascript] 단락 회로 평가 개념 및 활용 예제 (0) | 2022.02.23 |
| [javascript] Truthy & Falsy (0) | 2022.02.22 |
| [javascript] 함수 선언식과 함수 표현식 (0) | 2022.02.22 |
댓글