과거 프로그래밍 자료들/Javascript&typescript
모던 자바스크립트 핵심 가이드 06 디스트럭처링(destucturing)
평부
2022. 5. 16. 22:01
* 모던 자바스크립트 핵심 가이드(저자 알베르토 몬탈레시, 옮김 임지순/권영재) 복습
* 핵심 부분과 필요할 경우 문제도 수정해서 기재할 것
* 문제될 경우 삭제할 것
○ 디스트럭처링 특징 1
- 배열의 값 또는 객체의 속성을 풀어서 별개의 변수로 쓸 수 있게 해주는 자바스크립트 표현식
- Sanrio가 가진 속성에 접근함과 동시에 속성의 이름, 년도에 변수 선언이 가능해짐
//기존 객체에서 변수 생성 시
const Sanrio = {
name: "hello kitty",
year: 1974,
}
const name = Sanrio.name;
const year = Sanrio.year;
console.log(name, year); //"hello kitty" 1974
//디스트럭처링으로 객체에서 변수 생성 시
const Sanrio2 = {
name2: "my melody",
year2: 1975
}
const {name2, year2} = Sanrio2;
console.log(name2, year2); //"my melody" 1975
○ 디스트럭처링 특징2
- 중첩된 객체의 형태로 데이터가 주어지는 경우에도 동일한 방법으로 적용 가능
- 변수의 이름을 객체의 속성과 동일하게 지정하는 것에 그치지 않고 변수 이름도 바꿀 수 있음
const pokemon = {
name: "Pikachu",
number: 25,
type: {
classification: {
detail: "Electricity, mouse"
},
catchRate: 190
}
}
const {detail: pika} = pokemon.type.classification;
//type.classification.detail 프로퍼티를 찾아 pika라는 변수로 명칭
console.log(pika); //"Electricity, mouse"
console.log(detail); // detail is not defined
//변수를 pika로 다시 명명하고 기본값을 설정
const {detail: pikapika = "피카피카피카츄"} = pokemon.type.classification;
console.log(pikapika); //"Electricity, mouse"
○ 배열 디스트럭처링
- 객체의 디스트럭처링과 달리 {}가 아닌 [] 사용하기
const pokemon = ["Pikachu", "Bulbasaur", "Charmander", "Squirtle"];
const [electro, grass, fire, water] = pokemon;
console.log(electro, grass, fire, water) //"Pikachu", "Bulbasaur", "Charmander", "Squirtle"
//생성하려는 변수가 배열의 원소보다 적다면?
const pokemon2 = ["Pikachu", "Bulbasaur", "Charmander", "Squirtle"];
const [electro2, grass2, fire2] = pokemon2;
console.log(electro2, grass2, fire2); //Squirtle은 어디에도 할당되지 않음
//나머지 모든 값을 얻고 싶다면?
const korPokemon = ["피카츄", "이상해씨", "파이리", "꼬북이", "이브이"];
//레스트 연산자(...) 이용
const [전기, 풀, ...기타] = korPokemon;
console.log(...기타); //파이리, 꼬북이, 이브이
○ 변수 교체하기에 디스트럭처링 이용하기
let electro = "이브이"
let normal = "피카츄";
//피카츄는 전기포켓몬, 이브이는 노말포켓몬
[electro, normal] = [electro, normal];
console.log(electro, normal); //피카츄 이브이
문제 1
- 한 줄의 코드로 다음 배열의 각 값을 저장하는 변수 선언하기
let arr = ["one", "two", "three"];
let [one, two, three] = arr;
console.log(one); //one
console.log(two); //two
console.log(three); //three