模板文字和标记的模板文字之间的区别? [英] Difference between Template literals and Tagged template literals?

查看:100
本文介绍了模板文字和标记的模板文字之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6有两种新的文字:

ES6 has two new kinds of literals:


  • 模板文字

  • 标记的模板文字。

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

Template literals: multi-line string literals that support interpolation.

例如:

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

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

Tagged template literals : are function calls whose parameters are provided via template literals.

例如:

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

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

What is difference between these two literals ? and when to use Tagged template literals?

推荐答案

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

With tagged template literal we able to modify the output of template literals using a function. The first argument contains an array of string literals. The second, and each argument after the first one, are the values of the processed substitution expressions. We can use any name to our function.

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

这里我们的标签功能将使用自定义格式返回输出

here our our tag function will return the output with custom formats

这篇关于模板文字和标记的模板文字之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆