跳到主要内容

模版字符串

函数调用

const aVar = "good";
// fn是一个函数
fn`this is a ${aVar} day`;
fn(["this is a ", " day"], aVar);

解释:fn+模版字符串本质上一个函数调用。标签模板字符串会将模板字符串切割成多个参数构成的数组,将该数组作为参数传递给标签函数运行。假设这个参数数组为 params,params[0]为基于$对模板字符串进行split操作后的字符串数组,params[0]~params[n]依次为模板字符串中的$变量。

example

let greetings = "Hi";
let name = "Techsith";
let age = 35;

function transform(static, ...tags) {
console.log(static); // ["", " my name is ", " and I am ", ""]
console.log(tags); //["Hi", "Techsith", 35]
}

transform`${greetings} my name is ${name} and I am ${age}`;

使用场景:函数需要传的参数更倾向于一个整体的字符串表达式而不是多个参数。

let amount = 10.3;
i18n`You owe me ${amount}$`;
//spanish : Me debes 10.30€
//french: Tu me dois 10,30€