ES6寫法優(yōu)化 字符串模板

基礎(chǔ)寫法
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)
// 打印結(jié)果
<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> */
// 打印結(jié)果:
// a --- sentence
// Jelly has commented on your topic Learn to use markdown
// b --- sentence
// havana 說明標簽模板字符串的返回是由標簽來決定的
標簽模板字符串01.jpg
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容