본문으둜 κ±΄λ„ˆλ›°κΈ°

Tagged templates

funcstring`` 처럼 ν…œν”Œλ¦Ώ λ¦¬ν„°λŸ΄(template literals) μ•žμ— νƒœκ·Έ(ν•¨μˆ˜)λ₯Ό μ‚¬μš©ν•˜λ©΄ν…œν”Œλ¦Ώ λ¦¬ν„°λŸ΄μ„ νŒŒμ‹±ν•  수 μžˆλ‹€.

μ΄λ ‡κ²Œ μ‚¬μš©λ˜λŠ” νƒœκ·Έ ν•¨μˆ˜(Tag function)μ—λŠ” 첫 번째 인수둜 λ¬Έμžμ—΄ κ°’μ˜ 배열이 μ „λ‹¬λ˜κ³ , λ‚˜λ¨Έμ§€ μΈμˆ˜λ‘œλŠ” ν‘œν˜„μ‹μ΄ μ „λ‹¬λœλ‹€.

const person = 'Mike';const age = 28;
function myTag(strings, personExp, ageExp) {    console.log(strings); // ["that ", " is a ", "", raw: Array(3)]    const str0 = strings[0];    const str1 = strings[1];
    const ageStr = ageExp > 99 ? 'centenarian' : 'youngster';
    return str0 + personExp + str1 + ageStr;}
const output = myTag`that ${person} is a ${age}`;
console.log(output);// that Mike is a youngster

ν‘œν˜„μ‹μ΄ μ—¬λŸ¬ 개일 κ²½μš°μ— νƒœκ·Έ ν•¨μˆ˜μ—μ„œ λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜(Rest parameters)λ₯Ό μ‚¬μš©ν•˜λ©΄ λ°°μ—΄λ‘œ ν‘œν˜„μ‹μ„ λ°›μ•„ μ‚¬μš©ν•  수 μžˆλ‹€.

function myTag(strings, ...expressions) {    console.log(strings); // ["that ", " is a ", "", raw: Array(3)]    console.log(expressions); // ["Mike", 28]}
const person = 'Mike';const age = 28;
const output = myTag`that ${person} is a ${age}`;