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 = `

Hello

` console.log(template) // 打印结果

Hello

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

    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 的样式
/*  */
// 打印结果:
// a --- sentence
// Jelly has commented on your topic Learn to use markdown
// b --- sentence
// havana 说明标签模板字符串的返回是由标签来决定的
标签模板字符串01.jpg

你可能感兴趣的:(ES6写法优化 字符串模板)