배열이나 객체에서 원하는 값을 더 쉽고 빠르게 뽑아내는 방법
배열의 비 구조화 할당 (배열의 인덱스를 기준으로)
- 대괄호 [ ] 를 이용해 배열의 값을 순서대로 할당받아서 사용할 수 있다.
let arr = ["one", "two", "three"];
let [one,two,three]=arr;
// let one = arr[0];
// let two = arr[1];
// let three = arr[2];
console.log(one,two,three);
배열의 선언 분리 비 구조화 할당
- 배열을 선언할 때 배열의 값을 분리한다.
let [one,two,three]=["one", "two", "three"];
// let one = arr[0];
// let two = arr[1];
// let three = arr[2];
console.log(one,two,three);
- 배열에 요소 추가 후 기본값 할당
let [one,two,three, **four="four"**]=["one", "two", "three"];
// let one = arr[0];
// let two = arr[1];
// let three = arr[2];
console.log(one,two,three, four);
Ex) swap에 활용되는 비 구조화 할당
let a=10;
let b=20;
let tmp=0;
tmp=a;
a=b;
b=tmp;
console.log(a,b);
⇒
let a=10;
let b=20;
[a,b]=[b,a];
console.log(a,b);
객체의 비구조화 할당 (key를 기준으로)
let object ={
one:"one",
two:"two",
three:"three"
};
let one = object.one;
let two = object.two;
let three=object["three"];
console.log(one,two,three);
⇒
let object ={
one:"one",
two:"two",
three:"three"
};
let {one, two, three}= object;
console.log(one,two,three);
- let {one, two, three}= object;
- 객체 object에서, one이라는 key의 value값을 가져와 변수 one에 담고 two라는 key의 value값을 가져와 변수 two에 담고 three이라는 key의 value값을 가져와 변수 three에 담는다.
let object ={ one:"one", two:"two", three:"three", name:"최영서" }; **let {one, two, name, three}= object;** console.log(one,two,three, name);
- 순서 상관없이 키 값을 기준으로 접근한다.
- 변수의 이름을 key 값이 아닌 다른 값으로 바꾸고 싶다면?
- let {one, two, name : myName, three}= object;
- name이라는 key 값을 기준으로 value 값을 가져와서 myName이라는 변수에 할당하겠다는 뜻
- let {one, two, name : myName, three}= object;
- 프로퍼티를 추가하여 기본값을 할당하고 싶다면?
- let {one, two, name : myName, three, abc="four" }= object;
'프론트엔드 > Java Script' 카테고리의 다른 글
JavaScript Sec02_7 동기&비동기 (0) | 2024.02.20 |
---|---|
JavaScript Sec 02_6 Spread 연산자 (0) | 2024.02.20 |
JavaScript Sec02_4 조건문 Upgrade (0) | 2024.02.20 |
JavaScript Sec 02_3 단락회로 평가 (0) | 2024.02.20 |
JavaScript Sec02_2 삼항 연산자 (0) | 2024.02.20 |