구조 분해 할당 (ES6)

홍진우·2020년 10월 28일
0

자바스크립트

목록 보기
11/11

객채와 배열은 자바스크립트에서 가장 많이 쓰이는 자료 구조에요~!

key를 가진 데이터 여러 개를 하나의 엔티티에 저장할 땐 객체를,

컬렉션에 데이터를 순서대로 저장할 땐 배열을 사용하죠~

개발을 할 때 함수에 객체나 배열을 전달해야할 때가 있는데 저장된 데이터 전체가 아닌 일부만 필요한 경우가 생긴다는데 이럴 때 객체나 배열을 변수로 '분해'할 수 있게 해주는 특별한 문법이 구조 분해 할당이에요!!

배열 구조 분해

let users = ['Michael','Tom','Jane'];
let [user1, user2, user3] = users;

console.log(user1); //Michael
console.log(user2); //Tom
console.log(user14); //undefined

------------------------------------

//' ... '로 나머지 요소를 가져오기
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

console.log(name1); // Julius
console.log(name2); // Caesar

// `rest`는 배열이에요!
console.log(rest[0]); // Consul
console.log(rest[1]); // of the Roman Republic
console.log(rest.length); // 2

객체 구조 분해

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

let {title, width, height} = options;

console.log(title);  // Menu
console.log(width);  // 100
console.log(height); // 200

------------------------------------

//' ... '로 나머지 요소를 가져오기

// title = 이름이 title인 프로퍼티
// rest = 나머지 프로퍼티들
let {title, ...rest} = options;

// title엔 "Menu", rest엔 {height: 200, width: 100}이 할당됩니다.
alert(rest.height);  // 200
alert(rest.width);   // 100
profile
나는 나

0개의 댓글