Destructuring Assignment (구조 분해 할당)

송나은·2021년 6월 10일
1

JavaScript

목록 보기
23/23

Destructuring Assignment

객체나 배열을 변수로 '분해'할 수 있게 해주는 문법

1. 배열 분해하기

const arr = [1, 2, 3, 4];
const [first, second, , fourth] = arr;
/* 배열의 요소를 직접 변수에 할당하는 방법
const first = arr[0];
const second = arr[1];
*/

console.log(first) // 1
console.log(second) // 2
console.log(fourth) // 4

// 모든 이터러블(반복 가능한 객체)에 구조 분해 할당 적용이 가능하다.
const [a, b, c] = "abc"

console.log(a,b,c) // 'a' 'b' 'c'

const user = {};
[user.name, user.surname] = "Tomi Song".split(' ')

console.log(user) // { name: 'Tomi', surname: 'Song'}

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

배열 앞쪽에 위치한 값 몇 개만 필요하고 그 이후 이어지는 나머지 값들은 한데 모아서 저장하고 싶을 때

const [name1, name2, ...rest]=["Naeun", "Tomi", "Joonsik", "Chanho"]

console.log(name1) // "Naeun"
console.log(name2) // "Tomi"
console.log(rest) // ["Joonsik", "Chanho"]

2. 객체 분해하기

const options = {
  title: "Menu",
  width: 100,
};

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

console.log(title);  // Menu
console.log(w);      // 100
console.log(h);      // 200
console.log(options); // { title: "Menu", width: 100  }

3. 리액트에서 자주 사용하던 구조분해할당

// class형 컴포넌트
this.state = {
  user_name: "Tomi",
  user_password: token
}

const { user_name, user_password } = this.state

// 함수형 컴포넌트
const [ Index, setIndex ] = useState(0);

Reference

profile
그때그때 공부한 내용과 생각을 기록하는 블로그입니다.

0개의 댓글