JavaScript ES6模板字符串的类型不一致

jri*_*ich 7 javascript ecmascript-6 template-strings

在测试JavaScript ES6的新模板字符串时(在Firefox中,如果它很重要),我注意到它们的类型有些不一致.

我定义了一个自定义函数,如下所示:

function f(a) {
    console.log(typeof(a));
    console.log(a);
}
Run Code Online (Sandbox Code Playgroud)

首先,我使用模板字符串周围的括号测试了"正常"功能.

f(`Hello, World!`)
Run Code Online (Sandbox Code Playgroud)

正如所料,这产生了一种类型stringHello, World!输出到控制台.

然后我调用函数速记,没有括号,并且发生了不一致.

f`Hello, World!`
Run Code Online (Sandbox Code Playgroud)

类型变为object,并Array [ "Hello, World!" ]输出到控制台.

使用第二种方法时,为什么模板字符串包含在数组中?这只是Firefox中的一个错误(毕竟ES6 一个新标准)还是出于某种原因预期会出现这种情况?

log*_*yth 2

// A function call, passed the result of a template literal.
f(`str`)
Run Code Online (Sandbox Code Playgroud)

// A tagged template call, passed metadata about a template.
f`str`
Run Code Online (Sandbox Code Playgroud)

不一样。第一个调用f使用单个字符串作为参数。第二个调用f带有多个参数,具体取决于模板。例如

f`one${2}three${4}five`
Run Code Online (Sandbox Code Playgroud)

会过去的f

f(strings, ...values)
Run Code Online (Sandbox Code Playgroud)

strings
// ['one', 'three', 'five']
Run Code Online (Sandbox Code Playgroud)

这是模板的所有字符串部分的列表,以及

values
// [2, 4]
Run Code Online (Sandbox Code Playgroud)

这是字符串之间适合的所有值。这允许标签预处理字符串并处理它。

MDN 上的文档可以提供更多帮助