Es6-模板字符串

95 阅读1分钟

①模板字符串

1.认识模板字符串

`alex`
'alex'
"alex"

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='第一行\n第二行';
console.log(info);

模板字符串

    const into=`第一行\n第二行`
    const info=`第一行
第二行`;
    console.log(info);

模板字符串中,所有的空格,换行或者缩进,都会保留在输出之中

2.输出`和\等特殊字符

const info=`'\`\\`

console.log(info);

3.模板字符串的注入

// ${}
const username = "alax";
const person = [age, sex, "male"];
const getset = function (sex) {
  return sex === "male" ? "男" : "女";
};
const info=`${username},${person.age+2},${getSex(person.sex)}`;
console.log(info);

只要最终可以得出一个值就可以通过${}注入模板字符串中

③模板字符串的应用

<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: "wangguangwei",
          age: 18,
          sex: "female",
        },
        {
          username: "lisi",
          age: 38,
          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>