ES6语序我们用反引号
` 来定义我们的字符串,可以不需要用 +
来拼接字符串。如果字符串里面需要使用到变量的时候可以使用${variable}
,甚至可以在 {}
中使用js表达式。
const dp = {
name: 'dp',
todos: [
{ name: 'go to store', completed: false },
{ name: 'watch movie', completed: false },
{ name: 'running', completed: true },
]
}
const templete = `
<ul>
${dp.todos.map(todo => `<li>${todo.name} ${todo.completed ? '√' : 'X'}</li>`).join('')}
</ul>
`;
console.log(templete);
function highlight(strings, ...values) {
const highlighted = values.map(value => `<span class="highlight">${value}</span>`);
return strings.reduce((prev, curr, i) => `${prev}${curr}${highted[i] || ''}`, '');
}
const user = 'Marry';
const topic = 'Learn to use markdown';
const sentence = highlight`Dp ${user} has commented on your topic ${topic}`;
document.body.innerHTML = sentence;