ES6——模板字符串

本文介绍了ES6中模板字符串的特点,包括使用反引号表示、简化字符串拼接、支持多行编写以及允许在字符串中嵌入表达式和函数,提高了JavaScript代码的可读性和简洁性。
摘要由CSDN通过智能技术生成

与普通字符串的区别

相较于普通字符串,模板字符串使用反引号 ` 来代替普通字符串中的用双引号 " 和单引号 ’ ,模板字符串省去了大量 + 和 " 的使用,方便阅读和编写

  <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;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值