樣板字面值
說明ES6語法樣板字面值及跳脫字元
樣板字面值(Template literals)是允許嵌入運算式的字串字面值(string literals)。你可以透過樣板字面值來使用多行字串及字串內插(string interpolation)功能。他們在 ES2015 規範的先行版本中被稱為「樣板字串(template strings)」。-MDN:樣板字面值
語法
基本語法如下:
1 2 3 4 5 6 7 8 9 10 11
| `string text`
`string text line 1 string text line 2`
`string text ${expression} string text`
tag `string text ${expression} string text`
|
以白話點去說的話,我們以舉例去作說明,一般我們撰寫多行字串為
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const people = [ { name: 'mike', age: 2 }, { name: 'amy', age: 23 }, { name: 'jack', age: 34 } ]
let originString = '我叫做 ' + people[0].name; let orginAge = '<ul>\ <li>我叫做 ' + people[0].name + '</li>\ <li>我叫做 ' + people[1].name + '</li>\ <li>我叫做 ' + people[2].name + '</li>\ </ul>';
|
假如以樣板字面值寫法撰寫的話,
1 2 3 4 5 6 7 8 9 10 11
| let string = `我叫做 ${people[0].name}`
let ul = ` <ul> <li>我叫做 ${people[0].name}</li> <li>我叫做 ${people[1].name}</li> <li>我叫做 ${people[2].name}</li> </ul> `
|
跳脫字元
假如需要插入特殊字元,仍可以使用\
反斜線作插入:
1 2 3 4 5
| console.log(`\$$`);
console.log(`\$$`.length)
|
參考資料: