Blogger Information
Blog 94
fans 0
comment 0
visits 92727
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】JS之模板字面量与模板函数
可乐随笔
Original
553 people have browsed it

模板字面量与模板函数

1. 模板字面量

  1. //字符串的二大痛点
  2. // 1. 多行字符串
  3. // 过时写法 1
  4. // let str = '<ul>\n\
  5. // <li>1</li>\n\
  6. // <li>2</li>\n\
  7. // </ul>'
  8. // console.log(str)
  9. // 过时写法 2
  10. // let arr =['<ul>\n','<li>1</li>\n','<li>2</li>\n','</ul>\n']
  11. // str=arr.join('')
  12. // console.log(str)
  13. //* ES6 模板字面量写法,最好的写法
  14. const str = `<ul>
  15. <li>1</li>
  16. <li>2</li>
  17. </ul>`
  18. console.log(str)

2. 字符串,嵌入表达式(变量/插值)

  1. // php:双引号
  2. console.log('-------------------------')
  3. // +
  4. let a = 10
  5. let b = 20
  6. const str1 = a + '+' + b + ' = ' + (a + b)
  7. console.log(str1)
  8. //10+20=30
  9. console.log('-------------------------')
  10. a = 20
  11. b = 30
  12. //ES6 : 模板字面量
  13. const str2 = `${a}+${b} = ${a + b}`
  14. console.log(str2)
  15. console.log('-------------------------')

2.模板函数

模板字面量组成部分

  1. // * 1.字符串字面量: + , = , 空格
  2. // * 2.表达式: 变量, a, b
  3. // 声明一个模板函数
  4. const sum = function (strings, ...args) {
  5. //输出字面量数组
  6. console.log(strings)
  7. console.log(strings.length)
  8. //输出变量表达式数组
  9. console.log(args)
  10. console.log(args.length)
  11. // **! 参数特点**
  12. // 1. 全是数组
  13. // 2. 字符串面量数组长度 = 变量数组长度 + 1
  14. // 3. 为什么加1,要确保返回的任然是一个字符串
  15. let result = ''
  16. for (let i = 0; i < strings.length; i++) {
  17. result += strings[i] + (args[i] ? args[i] : '')
  18. }
  19. console.log(result)
  20. }
  21. let num = 10
  22. let price = 180
  23. sum`商品金额 = ${num} * ${price} = ${num * price} 元`
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post