javascript ES6标签模板2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES6标签模板2相关的知识,希望对你有一定的参考价值。

const dict = {
    HTML: 'Hyper Text Markup Language',
    CSS: 'Cascading Style Sheets',
    JS: 'JavaScript'
};

/* Create the function we tag onto the template string. Tagging it to a template
string automatically returns the strings seperated by values as an array (strings)
and gives the values as the rest of the argument. */
function addAbrriviations(strings, ...values) {
    /* We use the es6 rest operator to get the rest of all the values */
    const abbreviated = values.map(value => {
        if(dict[value]) {
            return `<abbr title='${dict[value]}'>${value}</abbr>`;
        }
        return value;
    });
    
    // Using array.reduce which takes in a function and an optional initial value
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
    return strings.reduce((sentence, string, i) => {
        return `${sentence}${string}${abbreviated[i] || ''}`
    }, '');
  }

  const first = 'Arden';
  const last = 'de Raaij';
  const sentence = addAbrriviations`Hello, my name is ${first} ${last} and I love to code ${'HTML'}, ${'CSS'} and ${'JS'} `;
  const p = document.createElement('p');
  
  p.innerHTML = sentence;
  document.body.appendChild(p);

以上是关于javascript ES6标签模板2的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript高级ES6常见新特性:词法环境letconst模板字符串函数增强SymbolSetMap

ES6--反引号的标签使用

javascript - 你不容错过的es6模板写法

es6字符串模板总结

javascript ES6模板文字

javascript ES6 - 标记模板