javascript ES6 - 标记模板

Posted

tags:

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

/* The highlight function we tagged on to our template string
Arguments: An array of strings in between variables and the variables
We could use `strings, age, name` as arguments but using the spread operator
to get all the variables is better scalable. */
function highlight(strings, ...values) {
    let str = '';
    /* For each string we add both string and value to the let value. If value doesn't exist, 
    add empty string. */
    strings.forEach((string, i) => {
      str += `${string} <span class='hl'>${values[i] || ''}</span>`;
    });
    
    return str;
}

const name = 'Snickers';
const age = 100;
const gender = 'male'
// Tag the 'highlight' function to the template string, the template string 
// acts as arguments for the function
const sentence = highlight`My dog's name is ${name} and he is ${age} years old and he's a ${gender}`;

document.body.innerHTML = sentence;

console.log(sentence);

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

html 使用ES6和lit-html导入和标记模板

ES6字符串随笔

javascript ES6模板文字

javascript ES6标签模板2

javascript ES6 - 里面有模板字符串循环的模板字符串

es6 --- 功能