繁体   English   中英

模板文字和标记模板文字之间的区别?

[英]Difference between Template literals and Tagged template literals?

ES6 有两种新的字面量:

  • 模板文字
  • 标记的模板文字。

模板文字:支持插值的多行字符串文字。

例如:

const firstName = 'Jane';
console.log(`Hello ${firstName}! How are you today?`);

标记模板文字:是函数调用,其参数通过模板文字提供。

例如:

String.raw`Hello ${firstName}! How are you today?

这两个文字有什么区别? 何时使用标记模板文字?

使用标记模板文字,我们可以使用函数修改模板文字的输出。 第一个参数包含一个字符串文字数组。 第二个参数以及第一个参数之后的每个参数都是已处理的替换表达式的值。 我们可以对我们的函数使用任何名称。

var a = 1;
var b = 2;

function tag(strings, ...values) {
 console.log(strings[0]); // "One "
 console.log(strings[1]); // " Two"
 console.log(strings[2]); // " Three"
 console.log(values[0]); // 1
 console.log(values[1]); // 2
}

tag`One ${ a } Two ${ b } Three`;

// One 
// Two 
// Three
// 1
// 2

这里我们的标签函数将返回自定义格式的输出

ES6 有新特性

模板文字

标记模板文字(标记模板)

这使得使用字符串更容易。 您将文本包裹在“反引号”中

有了这个,我们可以:

1.内插变量

let foo = "abc";

console.log(`Welcome ${foo}`);  // Welcome abc

2.插入任何类型的表达式

console.log(`2+3 = ${2+3}`) // 2+3 = 5

3.用'和"双引号声明字符串,无需转义。

let foo = `foo is 'bar', "bar" is foo`

console.log(foo); // "foo is 'bar', "bar" is foo"

4. 多行字符串更简洁的语法

let text = `foo is bar

bar is foo`  

console.log(text);

//"foo is bar

//bar is foo"

5.标记模板,我们可以将模板文字传递给函数,方法如下:

let person = 'Mike';
let age = 28;

let output = myTag `that ${ person } is ${ age }`;

function myTag(strings, personExp, ageExp) {

//strings[0] gets value "that "
//strings[1] gets value " is "
//personExp  gets value " Mike "
//ageStr     gets value "28"

return strings[0] + personExp + strings[1] + ageExp;
}

console.log(output);

// that Mike is 28

6.String.raw,我们可以得到raw形式,这里是例子:

let text = String.raw `The "\n" newline won't result in a new line.'
console.log(text);
// The "\n" newline won't result in a new line.

希望这可以帮助!!!!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM