-
[모던 자바스크립트] 템플릿 리터럴, 디스트럭처링프론트엔드 개발자가 될거야./js 2023. 4. 18. 18:41
템플릿 리터럴
ES6에서 문자열을 삽입하는 방식이 변경되었다.
- 여러 줄 문자열 생성
전체를 백틱으로 감싸면 된다. 백슬래시의 지옥에서 벗어날 수 있다.
const content = `hello, my name is jeongeun how are you?`;
객체 디스트럭처링
- 객체에서 변수를 생성하기 쉬워졌다.
// 예전 var person = { first : "noh", last : "jeong eun", } var first = person.first; var last = person.last; // 현재 const person = { first : "noh", last : "jeong eun", } const {first, last} = person;
디스트럭처링을 이용하여 객체가 가진 속성에 접근함과 동시에 해당 속성 이름으로 변수 선언이 가능하다!
- 중첩된 객체 형태도 동일한 방법을 적용하면 된다.
const person = { first : "noh", last : "jeong eun", links : { social : { instagram: "www.instagram" } } } const { instagram } = person.links.social
변수의 이름도 바꿀 수 있다!
const { instagram: insta } = person.links.social
기본 값을 전달할 수도 있다!!
const { instagram: insta = "www.instagram.com/1" } = person.links.social
배열 디스트럭처링
const person = ["jeongeun", "frontend", 27]; const [name, job, age] = person;
- 생성하려는 변수의 수가 배열의 원소보다 작으면?
const person = ["jeongeun", "frontend", 27]; const [name, job] = person;
- 나머지 모든 값을 얻고 싶다면?
레스트 연산자를 사용하여 나머지 값 전체를 얻으면 된다!
const person = ['jeongeun', 'frontend', 'c', 'd', 'e', 'f', 'g']; const [name, job, ...alphabet] = person; console.log(alphabet) // ['c', 'd', 'e', 'f', 'g']
- 디스트럭처링으로 변수 교체하기
디스트럭처링 할당을 사용하면 변수의 값을 매우 쉽게 서로 교체할 수 있다!!!
let hungry = 'yes'; let full = 'no'; [hungry, full] = [full, hungry]; console.log(hungry, full) // no yes
'프론트엔드 개발자가 될거야. > js' 카테고리의 다른 글
[모던 자바스크립트] 세트, 문자열 패딩 (0) 2023.04.19 [모던 자바스크립트] 루프 (0) 2023.04.19 [모던 자바스크립트] 함수 기본값 인수 (0) 2023.04.18 위코드 2주차 중간시험 리뷰 (0) 2022.07.01 [instagram 클론코딩] input 창에 엔터치거나 "게시"누르면 댓글 추가 구현하기 (0) 2022.06.29