[JS]구조분해할당

이동현·2021년 5월 2일
0

자바스크립트를 공부하면서 구조분해할당이(destructive assignment) 잘 이해가 되지않았다.
Nodejs를 활용한 클론 코딩도 해보했지만 그 과정에서도 구조분해할당이 나오면 이해를 못한채 코드를 배끼고 있었다.
구조분해할당에 관해 공부한 내용을 정리해보고자 한다.

Javsscript에서 함수를 만들때 객체나 배열을 함수에 전달하는 경우가 있다. 객체나 배열을 그대로 전달할 수 있지만 객체나 배열의 데이터중 일부만 전달하고자 할때 구조분해할당을 사용할 수 있다.

1. 배열(array)

구조분해 할당 적용하지 않았을 경우
let myArray = ['a',2,'다','d',5];

let abc = myArray[2];
let def = myArray[4];

console.log(abc)// '다'
console.log(def)// 5

배열의 구조분해 할당 적용

let myArray = ['a',2,'다','d',5];

let[,,abc,,def] = myArray

console.log(abc)// '다'
console.log(def)// 5

기본값

//할당할 값이 없는 경우 undefined로 할당되므로 분해하고자 하는 배열의 길이보다 많은 변수를
//할당연산자 좌측에 집어 넣더라도 에러가 발생하지 않는다.
let [apple,orange] = [];

console.log(apple) // undefined
console.log(orange)// undefined
//특정한 기본값을 부여하고 싶은경우 '=' 를 사용하여 default값을 설정해 줄수 있다.
let [apple,orange="맛있다"] = [];//orange변수에 dafault값을 설정

console.log(apple) // undefined
console.log(orange)// "맛있다"
//값을 할당해 준 경우 기본값 대신 할당된 값이 적용된다.
let [apple="빨간색",orange] = ["얼음골사과"];//apple변수에 dafault값을 설정

console.log(apple) // "얼음골사과"
console.log(orange)// undefined
  • 배열을 반환하는 Method를 사용할 때도 활용이 가능하다.

  • 구조분해할당(Destructuring assignment)시 에는 기존배열이나 객체를 분해하는것이 아니고 복사한 후 구조분해할당을 진행하므로 기존 객체나 배열에는 아무런 영향이 없다.

2. 객체(object)

객체의 구조분해할당도 유사하게 적용할수 있다.

let testObj = {name:"John",age:"21",adress:{country:"Korea",city:"Busan"}}

let {name,age,adress} = testObj;
console.log(name);//"John"
console.log(age);//"21"
console.log(adress)://{country:"Korea",city:"Busan"}

:을 사용하면 객체의 property와 다른 이름의 변수에 값을 할당할 수 있다.


let testObj = {name:"John",age:"21",adress:{country:"Korea",city:"Busan"}}

let {name:whatIsYourName, age, adress} = testObj;

console.log(whatIsYourName)//"John"
console.log(age);//"21"
console.log(adress);//{country:"Korea",city:"Busan"}

객체가 가진 정보를 선택적으로 할당하는것도 가능하다.

let testObj = {name:"John",age:"21",adress:{country:"Korea",city:"Busan"}}

let {age} = testObj;

console.log(age);//"21"
console.log(adress);//에러발생 ReferenceError: adress is not defined

중첩 구조 분해도 가능하다.

let testObj = {name:"John",age:"21",adress:{country:"Korea",city:"Busan"}}

let {adress:{city}} = testObj;

console.log(city)//"Busan"
console.log(adress);//에러발생
// 객체내의 adress property는 새롭게 할당해주지 않았고 adress의 value인 객체({country:"Korea",city:"Busan"})의 city property를 할당해준 것이므로에러가 발생한다.

부족한 내용은 계속 추가하면서 공부를 해나갈 예정이다. 위 자료를 정리하고 구조분해할당 예제를 연습하면서 객체의 구조분해할당을 약간 이해할 수 있었다.

참고문헌 : https://ko.javascript.info/destructuring-assignment

0개의 댓글