与普通字符串的区别
相较于普通字符串,模板字符串使用反引号 ` 来代替普通字符串中的用双引号 " 和单引号 ’ ,模板字符串省去了大量 + 和 " 的使用,方便阅读和编写
<script>
const name = "张三";
const age = "18";
const sex = "男";
const normal = "他叫" + name + ",是一名" + age + "岁的" + sex + "人";
const template = `他叫${name},是一名${age}岁的${sex}人`;
document.getElementById("normal").innerText = normal;
document.getElementById("template").innerText = template;
</script>
模板字符串支持多行编写
const normal =
"名字:" + name +
"年龄:" + age +
"性别:" + sex;
const template = `
名字: ${name}
年龄: ${age}
性别: ${sex}
`
document.getElementById("normal").innerText = normal;
document.getElementById("template").innerText = template;
输出结果:
模板字符串内也可以正常使用函数以及表达式
const name = "张三";
const age = "18";
const sex = "男";
function fn(name) {
return name + "成年了吗?";
}
const template = `
${fn(name)}
${age >= 18 ? "成年了" : "没成年"}
`;
document.getElementById("template").innerText = template;