认识模板字符串:
const username1 = 'alex';
// "alex"
const username2 = `alex`;
console.log(username1, username2, username1 === username2); // alex alex true
//模板字符串也可存入字符串
模板字符串与一般字符串的区别:
1、和其他东西一起使用的时候,使用模板字符串,方便注入。
2、 其他情况下使用模板字符串或一般字符串都行。
具体见下面的例子:
// 声明一个对象:
const person = {
username: 'Alex',
age: 18,
sex: 'male'
};
// 使用一般字符串需要拼接,较麻烦
const info =
'我的名字是:' +
person.username +
', 性别:' +
person.sex +
', 今年' +
person.age +
'岁了';
console.log(info);
// 使用模板字符串相对方便一些,将变量放入&{}即可
const info = `我的名字是:${person.username}, 性别:${person.sex}, 今年${person.age}岁了`;
console.log(info);
模板字符串的注意事项:
(1)输出多行字符串:
一般字符串:const info = '第1行\n第2行'; console.log(info);
模板字符串:
// 法1:可以继承一般字符串的写法:
const info = `第1行\n第2行`;
console.log(info);
// 法2:使用模板字符串的独特写法:
const info = `第1行
第2行`; // 注意:这种写法时,前面文字 '第2行' 必须顶头写否则中间会有空格与方法一不一致
console.log(info);
总结:模板字符串中,所有的空格、换行或缩进都会被保留在输出之中!所以写的时候一定要注意有没有多余的空格 换行 缩进。
(2)输出 ` 和 \ 等特殊字符:
const info = `'\`\\`;
console.log(info); // '`\
总结:就是通过 \ 对 ` 和 \ 等特殊字符进行转义。
(3)模板字符串的注入:
const username = 'alex';
const person = { age: 18, sex: 'male' };
const getSex = function (sex) {
return sex === 'male' ? '男' : '女';
};
const info = `${username}, ${person.age + 2}, ${getSex(person.sex)}`;
console.log(info); // alex, 20, 男
总结:上例中函数和加法式可以注入到模板字符串中,在实际中只要最终可以得出一个值的就可以通过 ${} 注入到模板字符串中。
模板字符串的应用:
举个栗子—利用模板字符串将东西注入进去:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>模板字符串的应用</title>
<style>
body {
padding: 50px 0 0 300px;
font-size: 22px;
}
ul {
padding: 0;
}
p {
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>学生信息表</p>
<ul id="list">
<li style="list-style: none;">信息加载中……</li>
</ul>
<script>
// 数据
const students = [
{
username: 'Alex',
age: 18,
sex: 'male'
},
{
username: 'ZhangSan',
age: 28,
sex: 'male'
},
{
username: 'LiSi',
age: 20,
sex: 'female'
}
];
const list = document.getElementById('list');
let html = '';
for (let i = 0; i < students.length; i++) {
html += `<li>我的名字是:${students[i].username},${students[i].sex},${students[i].age}</li>`;
}
list.innerHTML = html; // 将模板字符串注入的东西呈现出来
</script>
</body>
</html>
只要掌握了模板字符串怎么注入也就掌握了模板字符串了!