ES6-字符串扩展-模板字符串

来源:互联网 发布:vim c语言语法高亮 编辑:程序博客网 时间:2024/05/19 12:24

传统的 JavaScript 语言,输出模板语句是这样写的。

$('#id').append(  'There are <b>' + basket.count + '</b> ' +  'items in your basket, ' +  '<em>' + basket.onSale +  '</em> are on sale!');
ES6 引入了模板字符串,写法比较简单。

$('#id').append(`  There are <b>${basket.count}</b> items   in your basket, <em>${basket.onSale}</em>  are on sale!`);
模板字符串实增强版的字符串,用反引号(·)标识,它可以当做普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

// 普通字符串`In JavaScript '\n' is a line-feed.`// 多行字符串`string text line 1\`string text line 2`// 字符串中嵌入变量let name = "Bob", time = "today";`Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
1)如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。上面代码第二段所示。
2)如果使用模板字符串表示多行字符串,则所有的空格和缩进都会保留在输出之中。

`<ul>  <li>first</li>  <li>second</li></ul>`
3)上面代码的偶有模板字符串的空格和换行都是别保留的,比如 <ul> 标签前面会有换行,如果不想要这个换行可以使用 trim() 方法消除它。

`<ul>  <li>first</li>  <li>second</li></ul>`.trim()
4)模板字符串中嵌入变量,需要将变量名写在 ${} 之中。

function authorize(user, action) {  if (!user.hasPrivilege(action)) {    throw new Error(      // 传统写法为      // 'User '      // + user.name      // + ' is not authorized to do '      // + action      // + '.'      `User ${user.name} is not authorized to do ${action}.`);  }}
花括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。

let x = 1;let y = 2;`${x} + ${y} = ${x + y}`// "1 + 2 = 3"`${x} + ${y * 2} = ${x + y * 2}`// "1 + 4 = 5"let obj = {x: 1, y: 2};`${obj.x + obj.y}`// "3"
模板字符串之中还能调用函数。

function fun() {return 'hello'}`${fun()}`  // hello
5)如果大括号的值不是字符串,将按照一般的规则转为字符串,比如,大括号中是一个对象,将默认调用对象的 toString 方法。如果模板字符串中的变量没有声明,将报错。

// 变量place没有声明let msg = `Hello, ${place}`;// 报错
6)如果大括号内部是一个字符串,将会原样输出。

`Hello ${'World'}`// "Hello World"
7)模板字符串可以嵌套

const tmpl = addrs => `  <table>  ${addrs.map(addr => `    <tr><td>${addr.first}</td></tr>    <tr><td>${addr.last}</td></tr>  `).join('')}  </table>`;
在上面代码中,模板字符串的变量之中,又嵌套了另外一个模板字符串,使用方法如下:

const data = [    { first: '<Jane>', last: 'Bond' },    { first: 'Lars', last: '<Croft>' },];console.log(tmpl(data));// <table>////   <tr><td><Jane></td></tr>//   <tr><td>Bond</td></tr>////   <tr><td>Lars</td></tr>//   <tr><td><Croft></td></tr>//// </table>
8)如果需要引用模板字符串本身,在需要时执行,可以这么写:

// 写法一let str = 'return ' + '`Hello ${name}!`';let func = new Function('name', str);func('Jack') // "Hello Jack!"// 写法二let str = '(name) => `Hello ${name}!`';let func = eval.call(null, str);func('Jack') // "Hello Jack!"

原创粉丝点击