ES6 lesson8 – es6模板字符串实例
首先我们准备一个对象(数据)
const Fea = { name: 'Fea Hsu', age: 26, todos: [ { name: 'Read book', complated: false }, { name: 'Chat with the girl', complated: true }, { name: 'Write blog', complated: false } ] }
我们现在来用字符串模板的形式展示一下Fea需要做的事情(todos
):
const template = ` <ul> <li>${Fea.todos[0].name}</li> <li>${Fea.todos[1].name}</li> <li>${Fea.todos[2].name}</li> <ul> ` document.body.innerHTML = template
- Read book
- Chat with the girl
- Write blog
可是一个个的粘贴看起来很low,且对付大量数据时,C和V键要按坏,所以稍加改造:
const template = ` <ul> ${ Fea.todos.map(todo => `<li>${ todo.name }</li>`).join('') } <ul> ` document.body.innerHTML = template
有木有看到,模板字符串是可以嵌套的,而且是无限嵌套。
我们再把上面的显示结果美化一下,可以用bootstrap。
最后我们把代码分离一下,变成下面这个样子:
function todoStatus (todos) { return `${ todos.map((todo, index) => ` <tr> <th scope="row">${ index + 1 }</th> <td>${ todo.name }</td> <td>${ todo.complated ? '完成' : '未完成' }</td> </tr> `).join('') }` } const template = ` <table class="table table-bordered"> <thead> <tr> <th>id</th> <th>Name</th> <th>Complated</th> </tr> </thead> <tbody> ${ todoStatus(Fea.todos) } </tbody> </table> ` document.body.innerHTML = template
这样子,就很完美了。
ES6还为我们新增了一些字符串的操作函数:
startWith()
endWith()
includes()
repeat()
本文系作者 @feacx 原创发布在 。未经许可,禁止转载。