ES6的模板字符串

178 阅读1分钟

什么是模板字符串

在ES6之前,如果我们想要将字符串和一些动态的变量(标识符)拼接到一起,是非常麻烦和丑陋的。首先,我们会使用 `` 符号来编写字符串,称之为模板字符串。其次,在模板字符串中,我们可以通过 ${expression} 来嵌入动态的内容。

//ES6之前拼接字符串和其他标识符
const name = "why"
const age = 18
const height = 1.88

console.log("my name is "+name); //这种代码比较丑陋

// ES6提供的模板字符串 ``

const message = `my name is${name} ,age is${age} ,height is${height}`
console.log(message); //语法可读性更加强了

const info1 = `age double is ${age * 2}` //${}后面可以写表达式的 
console.log(info1);

function doubleAge(){
   return age * 2
}

const info2 = `double age is ${doubleAge()}` //${}后面也是可以跟着函数的
console.log(info2);

标签模板字符串

模板字符串还有另外一种用法:标签模板字符串(Tagged Template Literals)。

//第一个参数依然是模板字符串中整个字符串,只是被切成多块,放到了一个数组中
//第二个参数是模板字符串中,第一个${}

//这是函数调用的一种方式
function foo(m,n){
   console.log(m,n,'---------');
}

foo("Hello","World")

const name = 'harry'
const age = 18
//这样也可以调用函数
foo`Hello${name}Wo${age}rld`  //[ 'Hello', 'Wo', 'rld' ] harry ---------
//它会形成一个数组通过${}切成三个 【'Hello','Wo', 'rld'] 第一个参数
//第二个参数就是name的值,harry

//这是为react all in js服务的
//将css in js,有一个非常流行的第三方库 styled-components,它利用的原理就是这个标签模板字符串