FE BE 개발 메모장/Javascript

구조 분해 할당

 만약 함수에 객체나 배열을 전달해야하는 경우가 생기거나, 객체나 배열에 저장된 데이터의 일부만 필요한 경우가 생길 때에 어떤 문법을 사용해야 효과적일지 고민이라면 '구조 분해 할당' 이라는 것을 한번 알아보자

 

배열 분해

let ramen = ["Jin Ramen", "Shin Ramen"]

//구조 분해 할당을 이용해 Aline에는 ramen[0]을
//Bline에는 ramen[1]을 할당했다.

let [lineA, lineB] = ramen;

console.log(lineA); // Jin Ramen
console.log(lineB); // Shin Ramen

spread Syntax로 나머지 요소 가져오기

 

배열 앞쪽에 위치한 값 몇개만 필요하고, 나머지는 한곳에 모아서 저장하고 싶다면, '...' 을 활용해 매개변수를 추가하면 나머지(rest)의 요소를 가져올 수 있다.

let [word1, word2, ...words] = ["culture","liberty","effect","symbol","education","experience"]

console.log(word1);          // culture
console.log(word2);          // liberty
console.log(...words);       // effect,symbol,education,experience
console.log(words.length);   // 4

 

 

객체 분해 

let options= {
  title: "menu",
  width: 100,
  height: 200
};

let {title, width, height} = options;

 

let options= {
  title: "menu",
  width: 100,
  height: 200
};

let {width: w, height: h, title} = options;

console.log(w)      // 100
console.log(h)      // 200
console.log(title)  // menu

spread Syntax로 나머지 요소 가져오기

 

배열에서 나머지 패턴을 사용했던 것처럼, 객체에서도 rest pattern을 사용할 수 있다. 분해하려는 객체의 프로퍼티 개수가 할당하려는 변수의 개수보다 많을 경우 유용한 방법이다.

let options= {
  title: "menu",
  width: 100,
  height: 200
};

let {title, ...size} = options;

console.log(title)       // menu
console.log(size.width)  // 100
console.log(size.height) // 200

 

 

함수 매개변수 

 

 

'FE BE 개발 메모장 > Javascript' 카테고리의 다른 글

Date 생성자  (0) 2021.03.17
ES-6 문법 정리  (0) 2021.02.10
Promise 메소드들...  (0) 2021.02.04
JSON에 대하여  (0) 2021.02.03
async & await  (0) 2021.02.02