본문 바로가기

Today`s Study

22.04.07 목

야구장 알바 끝나고 와서 쓰는 글입니다.

다행히 기아가 이겨서 9회 초만 하고 끝나 일찍 집에 올 수 있었네요

 

오늘은  야구장 가기 전에 잠깐 강의를 보았습니다.

 

1. 비 구조화 할당

대괄호를 사용해서 값을 순서대로 할당받는 문법으로 객체, 배열에 쓰인다.

let arr = ["one", "two", "three"];
let [one, two, three] = arr;
console.log(one, two, three) // one, two, three

// 여기서 더 줄일 수 있다.
let [one, two, three] = ["one", "two", "three"]
console.log(one, two, three) // one, two, three

// 선언되지 않은 값을 부르면 undefined
let [one, two, three, four] = ["one", "two", "three"];
console.log(one, two, three, four) // one, two, three, undefined
 
//undefined를 주지 않고 기본값을 넣을 수 있다.
let [one, two, three, four="four"] = ["one", "two", "three"];

 

비 구조화 할당을 이용해서 스왑을 할 수 있다.

//기존에는 이렇게 진행했다.
let a = 10;
let b = 20;
let tem = 0;

tmp = a;
a = b;
b = tmp;

console.log(a, b) // 20 10

//비 구조화 할당을 사용해 스왑한 코드

let a = 10;
let b = 20;

[a, b] = [b, a]
console.log(a, b);

 

객체의 비구조화 할당

index 기준이 아닌 키 값을 기준으로 할당한다.

let object = { one: "one", two: "two", three: "three" };

let one = object.one;
let two = object.two;
let three = object.three;

console.log(one, two, three);

 
//비 구조화 할당을 사용해 줄인 코드

let object = { one: "one", two: "two", three: "three" };

let { one, two, three } = object;
console.log(one, two, three);

 

또한 변수명을 바꿀 수 있으며 기본값 설정도 가능하다

// 변수명 변경
let object = { one: "one", two: "two", three: "three", name: "이정환" };

let { name: myName one, two, three } = object;
console.log(one, two, three, myName);  // one, two, three, 이정환

 
//기본값 설정
let { name: myName one, two, three } = object;
console.log(one, two, three, myName, abc="four");  // one, two, three, 이정환 four

 

 

2. spread 연산자 (...)

spread연산자는 객체나 배열을 펼쳐놓습니다. 이는 우리가 객체 내 중복되는 프로퍼티나 배열의 요소를 꺼내 쓸 때 유용합니다.

// 객체
const cookie = {
  base: "cookie",
  madeIn: "korea"
};

const chocochipCookie = {
  ...cookie
  toping: "choccochip"
}

const blueberryCookie = {
  ...cookie
  toping: "blueberry"
}

// 배열
const noTopingCookies = ["촉촉한쿠키", "안촉촉한쿠키"];
const topingCookies = ["바나나쿠키", "딸기쿠키", "블루베리쿠키", "초코칩쿠키"];
const allcookies = [...noTopingCookies, ...topingCookies, "포도쿠키"]

 

메서드 concat과 다른 점은 중간에 값을 넣을 수 있다는 점입니다.

 

여기까지 오늘 공부해보았습니다.

728x90

'Today`s Study' 카테고리의 다른 글

22.04.10.일 [Promise]  (0) 2022.04.10
22.04.09 토  (0) 2022.04.09
22.04.06 수  (0) 2022.04.07
22.04.05 화  (0) 2022.04.06
22.04.04 월  (0) 2022.04.05