ES6 - template literal

2020. 7. 21. 12:45·JS
목차
  1. template literal
  2. 상세
  3. 번외 - forEach, map, reduce
  4. forEach
  5.  
  6. map
  7. reduce
  8. String.raw

template literal

 

template literal은 문자열이다. 

문자열 선언하는 방식은 

var a= 'abc'

var b = "abc"

var c = `abc`

 

a === b

b === c

a === c

 

string literal // 문자 그대로의

 

``은 줄바꿈을 할때 공백을 그대로 출력하기 때문에 주의해야 한다.

var a = 'abc\n' +
    'def'
console.log(a);
//
abc
def
var b = `a
    bb
    ccc`;
console.log(b)

//
a
    bb
    ccc
const a = 10
const b = 20
const strBefore = a + '+' + b + '=' + (a + b);
const str = `${a} + ${b} = ${ a + b }`;
console.log(strBefore, str);

//
10+20=30 10 + 20 = 30

 

상세

 

1) backtick(`)

2) multi - line  = 줄바꿈이 된다.

3) string interporation  = ${a}

 

 

multi-line의 경우 들여쓰기에 주의

const f = function (){
    const a = `abc
    def
    ghij`
    console.log(a);
}
f()
//
abc
    def
    ghij

 

${ } 내에는 값 또는 식 이 올 수 있다.

 

const counter = {
  current: 0,
  step: 1,
  count: function() { return this.current += this.step },
  reset: function() { return this.current = 0 }
}
console.log(`${counter.count()} ${counter.count()}
${counter.reset()} $${counter.count()}
${counter.count()}$`)

 

 

번외 - forEach, map, reduce

forEach

 

 

const a = [ 1, 2, 3 ]
a.forEach(function (v, i, arr) {
    console.log(v, i, arr, this)
}, [ 10, 11, 12 ])

 

map

const a = [ 1, 2, 3 ]
const b = a.map(function (v, i, arr) {
    console.log(v, i, arr, this)
    return this[0] + v
}, [ 10 ])

 

reduce

 

const arr = [ 1, 2, 3 ]
const res = arr.reduce(function (p, c, i, arr) {
  console.log(p, c, i, arr, this)
  return p + c
}, 10)
const arr = [ 1, 2, 3, 4 ]
const str = arr.reduce(function (res, item, index, array) {
  return res + item
}, '')
const arr = [ 'a', 'b', 'c', 'd' ]
const str = arr.reduce(function (res, item, index, array) {
  return res + item
})
console.log(str)
const arr = [ 10, 20, 30, 40, 50 ]
const r = arr.reduce(function (p, c) {
  return p + c
})
console.log(r)
const arr = [ 10, 20, 30, 40, 50 ]
const r = arr.reduce((p, c) => p + c)
console.log(r)

배열의 모든 메소드는 중요한 순서로 나열되어있다.

forEach : for문을 돌리는 거랑 같은 개념.

map :  for문을 돌려서 새로운 배열을 만드는 목적. return 필수

reduce : for문을 돌려서 최종적으로 다른 무언가를 만드는 목적. return 필수

 

 

String.raw

 

문자열이 담긴 배열을 열어보면  raw라는 프로퍼티가 보이는데 이는 strs와 인자가 같다는 것을 볼 수가 있다.

문자열 끝에 \n\n을 추가해서 다시 실행해보자

const tag = function(strs, ...args){
    return {strs: strs, args}
}
const res = tag `순서가 ${1}이렇게 ${2}${3}\n\n`;
console.log(res);

srts는 \n\n없이 문자열의 마지막 인자에 ""

raw라는 프로퍼티에는 문자열의 마지막 인자에 "\n\n"가 추가된 것을 알 수 있다.

 

console.log(`Hello\nWorld!`)
console.log(String.raw `Hello\nWorld!`)
console.log(String.raw `Hello
World!`)

string.raw가 없는 상태에서 문자열을 출력한 것과

string.raw가 있는 상태에서 문자열을 출력한 것을 비교해보면

다음과 같은 결과를 볼 수 있다. 요약하자면 string.raw는 이스케이프 문자 \n를 다음 줄로 바꾸는 것이 아니라

문자열로  출력해준다는 것을 알 수 있다.

'JS' 카테고리의 다른 글

제너레이터 함수  (0) 2022.02.06
default parameter (매개변수 기본값)  (0) 2020.07.21
ES6 - Block scope  (0) 2020.06.21
호이스팅  (0) 2020.06.14
클로저  (0) 2020.06.08
  1. template literal
  2. 상세
  3. 번외 - forEach, map, reduce
  4. forEach
  5.  
  6. map
  7. reduce
  8. String.raw
'JS' 카테고리의 다른 글
  • 제너레이터 함수
  • default parameter (매개변수 기본값)
  • ES6 - Block scope
  • 호이스팅
king_hd
king_hd
웹 개발 공부를 위한 블로그입니다.
king_hd
웹 개발 기록
king_hd
전체
오늘
어제
  • 분류 전체보기
    • HTML
    • CSS
    • JS
    • Typescript
    • React
    • nodejs
    • Redux
    • Git
    • 오류모음
    • Webpack
    • 자료구조
    • 네트워크
    • Electron
    • 배포
    • Docker
    • 프로그래머스

블로그 메뉴

  • 홈

링크

공지사항

인기 글

태그

리덕스
docker
4차산업혁명동아리
propertykey
웹개발
TAVE
docker mysql workbench 연동하는 법
Redux
mysqld: can't open file: 'mysql.ibd' (errno: 0 - )
인증서 자동갱신
env파일 환경변수 인식
https 인증서 발급
타입스크립트
next.js
webpack
코딩테스트
백엔드
const
프로그래머스
리덕스사가
웹퍼블리셔
JavaScript
자바스크립트
let
Hook
ec2에 docker 설치
Redux-saga
TypeScript
프론트엔드
react

최근 댓글

최근 글

hELLO· Designed By정상우.v4.6.0
king_hd
ES6 - template literal
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.