0x00 模板字符串
传统的JavaScript语言,输出模板一般是这样的写的。html
1 $('#result').append( 2 'There are <b>' + basket.count + '</b> ' + 3 'items in your basket, ' + 4 '<em>' + basket.onSale + 5 '</em> are on sale!' 6 );
上面这种写法至关繁琐不方便,ES6 引入了模板字符串解决这个问题。app
1 $('#result').append(` 2 There are <b>${basket.count}</b> items 3 in your basket, <em>${basket.onSale}</em> 4 are on sale! 5 `);
模板字符串(template string)是加强版的字符串,用反引号(`)标识。它能够看成普通字符串使用,也能够用来定义多行字符串,或者在字符串中嵌入变量post
// 普通字符串 `In JavaScript '\n' is a line-feed.` // 多行字符串 `In JavaScript this is not legal.` console.log(`string text line 1 string text line 2`); // 字符串中嵌入变量 let name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`
上面代码中的模板字符串,都是用反引号表示。若是在模板字符串中须要使用反引号,则前面要用反斜杠转义。this
let greeting = `\`Yo\` World!`;
输入结果:`Yo` World!spa
若是使用模板字符串表示多行字符串,全部的空格和缩进都会被保留在输出之中。code
$('#list').html(` <ul>
<li>first</li>
<li>second</li>
</ul>
`);