【问题标题】:Difference between Template literals and Tagged template literals?模板文字和标记模板文字之间的区别?
【发布时间】:2017-08-04 10:13:12
【问题描述】:

ES6 有两种新的字面量:

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

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

例如:

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

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

例如:

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

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

【问题讨论】:

  • 您是专门询问String.raw 还是一般的标记模板文字?
  • @FelixKling 我在询问标记模板文字。
  • ES6 tagged templates practical usability 会回答您的问题吗?模板文字和标记模板文字之间的区别在于后者允许您将自定义逻辑应用于模板文字(而不是默认的,即字符串连接)。

标签: javascript ecmascript-6


【解决方案1】:

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,我们可以得到原始形式,下面是例子:

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.

希望对你有帮助!!!!!!

【讨论】:

    【解决方案2】:

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

    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
    

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

    【讨论】:

    • “第一个参数包含一个字符串数组” nitpick:它包含一个字符串数组。文字是仅对解析器感兴趣的句法结构。解释器从它们创建字符串值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2019-08-25
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多