ES6写法优化 字符串模板

基础写法
const person = 'Jelly';
const age = 5;
// const sentence = person + ' is ' + age * 5 + ' years old.'; // 以前的写法
const sentence = `${person} is ${age * 5} years old.`; // 字符串模版写法
console.log(sentence); // Jelly is 25 years old.
html字符串更加简洁
const template = `
<div class="greet">
    <p>Hello</p>
</div>`
console.log(template)
// 打印结果
<div class="greet">
    <p>Hello</p>
</div>
const Jelly = {
    name: 'Jelly',
    date: '2019-07-06',
    todos: [
        { name: 'Go to Store', completed: false },
        { name: 'Watch Movie', completed: true },
        { name: 'Running', completed: true }
    ]   
}

const template = `
<ul>
    ${Jelly.todos.map(todo => `
    <li>
        ${todo.name} ${todo.completed ? '已完成' : '还没做'}
    </li>`).join('')}
</ul>
`
document.body.innerHTML(template); //输出到页面如下图:
字符串模版01.jpg
标签模板字符串:
function highlight(strings, ...values) {
    // b --- sentence
    // return 'havana'
        
    // c --- sentence
    const highlighted = values.map(value => `<span class="highlight">${value}</span>`);

    let str = ''
    strings.forEach((string, i) => str += `${string}${highlighted[i] || '' /*因为最后的value可能是undefined*/}`);
    return str;
}
const user = 'Jelly';
const topic = 'Learn to use markdown';
// a --- sentence
const sentence = `${user} has commented on your topic ${topic}`;
// b --- sentence
const sentence = highlight`${user} has commented on your topic ${topic}`;

console.log(sentence);
// c --- sentence 输出如下图:
document.body.innerHTML = sentence;
// c --- sentence 的样式
/* <style>
    .highlight {
        padding: 2px 5px;
        background: #00adb5;
        color: white;
    }
</style> */
// 打印结果:
// a --- sentence
// Jelly has commented on your topic Learn to use markdown
// b --- sentence
// havana 说明标签模板字符串的返回是由标签来决定的
标签模板字符串01.jpg
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容