概览

我们先来看一段代码:

  1. const name = 'wally'
  2. const age = 17
  3. function desc(strings, name, age) {
  4. console.log(strings, name, age) // [ '', ' 今年 ', ' 岁了' ] 'wally' 17
  5. }
  6. let str = desc`${name} 今年 ${age} 岁了`

模板字符串可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串。这被称为“标签模板”功能(tagged template)

上述代码中,desc这个函数后边跟了模板字符串。

desc的第一个参数:是一个数组,数组的成员是模板字符串被变量分割的一个个子字符串, [ '', ' 今年 ', ' 岁了' ]

除去第一个参数,往后的每个参数依次对应模板字符串中各个变量。

结合剩余参数使用

也可以使用es6中剩余参数,写成这样:

  1. function desc(strings, ...values) {
  2. console.log(strings, values) // [ '', ' 今年 ', ' 岁了' ] [ 'wally', 17 ]
  3. }

这段代码中的values就编程了数组: [ 'wally', 17 ] ,也就是模板字符串中的所有变量构成的一个数组

模板字符串机制的简单实现

  1. const name = 'wally'
  2. const age = 17
  3. let str = '${name} 今年 ${age} 岁了'
  4. // 模拟模板字符串的功能
  5. function templateString(str) {
  6. // 用正则表达式 将 ${name} -> name ${age} -> age
  7. return str.replace(/\$\{([^}]+)\}/g, function(matched, key) {
  8. console.log('matched, key: ', matched, key);
  9. // eval 将key字符串转换为变量
  10. return eval(key)
  11. })
  12. }
  13. console.log('templateString(str): ', templateString(str));

输出结果为:
code.png