ES6: 模版字符串

前言: ES5 中我们表示字符串的时候使用 '' 或者 ""

作用: 在 ES6 中,我们还有一个东西可以表示字符串,就是 ``(反引号)

let str = `hello world`console.log(typeof str) // string

和单引号还有双引号的区别:

  1. 反引号可以换行书写
// 这个单引号或者双引号不能换行,换行就会报错了
let str = 'hello world' 

// 下面这个就报错了
let str2 = 'hello 
world'
let str = ` 
	hello 
	world
`
console.log(str) // 是可以使用的 
  1. 反引号可以直接在字符串里拼接变量
// ES5 需要字符串拼接变量的时候
let num = 100
let str = 'hello' + num + 'world' + num
console.log(str) // hello100world100

// 直接写在字符串里面不好使
let str2 = 'hellonumworldnum'
console.log(str2) // hellonumworldnum
// 模版字符串拼接变量
let num = 100
let str = `hello${num}world${num}`
console.log(str) // hello100world100

里面的${} 就是用来书写变量的位置

实际应用:

更新数组初始值为列表元素

<body>
  <ul>

  </ul>
  <script>
    let arr = ["a", "b", "c"]
    let newlist = arr.map(function(item) {
      return `<li>
          <b>${item}</b>
        </li>`
    })
    console.log(newlist);
    
    let oul = document.querySelector("ul")
    oul.innerHTML = newlist.join("") // 不带jion的话, 每行之间会有,分隔
  </script>
</body>

效果:

升级版: 利用index可以实现指定li中字体颜色的转换

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .active {
      color: red;
    }
  </style>
</head>
<body>
  <ul>

  </ul>
  <script>
    let arr = ["a", "b", "c"]
    let newlist = arr.map(function(item, index) {  //添加index
      return `<li class="${index === 0 ? 'active' : ''}">  
          <b>${item}</b>
        </li>`
    })
    console.log(newlist);
    
    let oul = document.querySelector("ul")
    oul.innerHTML = newlist.join("") // 不带jion的话, 每行之间会有,分隔
  </script>
</body>
</html>

效果:

猜你喜欢

转载自blog.csdn.net/CaptainDrake/article/details/131545604