JavaScript 응용(구조 분해 할당)

Sujeong K·2022년 8월 15일
0

JavaScript_basic

목록 보기
11/17

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

배열의 비구조화 할당

let arr = ['Jane', 'Lee']
let [firstName, lastName] = arr;

console.log(firstName); // Jane
console.log(lastName); // Lee
  • 순서대로 요소가 변수에 할당됨
let arr = [1, 2, 3, 4, 5]
let [one, two, ...rest] = arr;

console.log(rest); // [3, 4, 5]
  • 나머지는 ...로 가져올 수 있음
let [a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
  • 변수에 기본값을 할당하면, 분해한 값이 undefined일 때 그 값을 대신 사용
//  swap
let apple = 1;
let banana = 2;
[apple, banana] = [banana, apple];
console.log(apple, banana); // 2 1
  • 두 변수의 값 교환하기
    *구조 분해 할당 없이 두 값을 교환하려면 임시 변수가 필요

객체의 비구조화 할당

let obj = { one: "one", two: "two", three: "three", name: "jane" t: true};
let { t, name, one, two, three } = obj;
console.log(one); // one
console.log(name); // jane
console.log(t); // true
  • 객체는 key 값을 기준으로 할당하기 때문에 변수 순서는 상관 없음

key값이 아닌 다른 이름의 변수에 할당하고 싶을 때

let { name: myName } = obj;
console.log(myName); // jane

기본값 설정과 새로운 변수 이름으로 할당을 같이 할 때

let { f: ff = false } = obj;
console.log(ff); // false

중첩구조분해

let video = {
  title: "cat",
  intro: "please watch",
  items: [1, 2]
};

function showThumnail({
  title = untitled,
  width = 200,
  height = 100,
  intro,
  items: [item1, item2]
}) {
  console.log(title, width, height); // width, height는 기본값
  console.log(intro);
}

showThumnail(video); 
// cat 200 100
// please watch

위와 같이 함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 유용

profile
차근차근 천천히

0개의 댓글