front-end-interview-handbook/packages/quiz/questions/es6-template-literals-offer.../zh-CN.mdx

63 lines
2.0 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: ES2015 模板字面量在生成字符串时具有很大的灵活性,您能给出一个例子吗?
---
模板字面量有助于简单地进行字符串插值,或在字符串中包含变量。 在 ES2015之前常见的做法是做这样的
```js
var person = {name: 'Tyler', age: 28};
console.log(
'Hi, my name is ' + person.name + ' and I am ' + person.age + ' years old!',
);
// 'Hi, my name is Tyler and I am 28 years old!'
```
使用模板字面量,您现在可以创建相同的结果像这样:
```js
const person = {name: 'Tyler', age: 28};
console.log(`Hi, my name is ${person.name} and I am ${person.age} years old!`);
// 'Hi, my name is Tyler and I am 28 years old!'
```
请注意您使用反引号而不是引号, 指示您使用的是一个字段,您可以在 "${}" 占位符中插入表达式。
第二个有用的案例是创建多行字符串。 在 ES2015之前您可以创建一个多行字符串像这样
```js
console.log('This is line one.\nThis is line two.');
// This is line one.
// This is line two.
```
或者如果你想要将它分成你的代码中的多行,所以你不必滚动到你的文本编辑器中的右边阅读一个长字符串, 你也可以像这样写:
```js
console.log('This is line one.\n' + 'This is line two.');
// This is line one.
// This is line two.
```
然而,模板字面量保留您添加到它们的任何空格、换行。 例如,要创建与我们在上面创建的相同的多行输出, 你可以简单地做:
```js
console.log(`This is line one.
This is line two.`);
// This is line one.
// This is line two.
```
模板字面量的另一个使用情况是作为简单变量插值的模板库的替代物:
```js
const person = {name: 'Tyler', age: 28};
document.body.innerHTML = `
<div>
<p>Name: ${person.name}</p>
<p>Age: ${person.age}</p>
</div>
`;
```
**注意你的代码可能会因为使用`.innerHTML`而受到XSS的影响。 如果数据来自一个用户,请在显示数据之前将其净化!**