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>

效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值