javascript - 模板文字和无括号函数调用

标签 javascript ecmascript-6 template-literals tagged-templates

我最近了解到 ES6 允许在使用模板文字作为参数时进行不带括号的函数调用。例如。

showstring`Hello World`;
然而,在阅读了几篇关于此功能的文章后,我发现关于 JS 如何处理这些调用背后的逻辑的信息很少。
在玩弄了我的代码的一些排列之后,我仍然在努力拼凑模板文字在以这种方式调用时如何在函数内部分解的模式。

const showstring = (str) => {
  console.log(str);
}
showstring`Hello World`;

上面代码中发生的事情很简单,字符串文字作为数组接收,其中第一个也是唯一的元素是字符串。
一旦我开始在模板中使用表达式,它就会变得有点困惑。例如。

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring`Hello World ${name} ${name} ${1 + 2} and more`;

所以它看起来像 ...values part 解构所有表达式。但是,为什么 str数组在那些位置有空字符串?
我只是没有完全掌握它遵循的模式。有人可以解释这个功能吗?或者也许给我指出一篇好文章?

最佳答案

在第二个代码片段中,记录了以下内容:

// str
[
  "Hello World ",
  " ",
  " ",
  " and more"
]

// values
[
  "John",
  "John",
  3
]
如果这些“空字符串”是指 str 的第 2 项和第 3 项数组,它们不是空字符串;它们是带有单个空格的字符串。它们来自模板文字中表达式之间的空格:
showstring`Hello World ${name} ${name} ${1 + 2} and more`;
//                            ^       ^

当模板文字前面有一个表达式时——在这种情况下是 showstring – 它被称为 tagged template .
在您的 showstring函数, str总是比 values 多一项大批。例如。看看这些日志:

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring``;
showstring`${name}`;
showstring`Hello ${name}!`;

这不是特定于您的功能;这就是标记模板的工作方式。来自 Tagged templates section in the book JavaScript for impatient programmers (ES2020 edition) :

The function before the first backtick is called a tag function. Its arguments are:

  • Template strings (first argument): an Array with the text fragments surrounding the interpolations ${}.
  • Substitutions (remaining arguments): the interpolated values.


关于您的评论:

Interestingly though, that single space will always remain a single space no matter how many spaces you put between the expressions when calling the function. Any idea why it trims to just one space?


情况似乎并非如此。这会记录一个包含三个空格的字符串:

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring`Hello ${name}   ${name}!`;

您是否可能将结果打印到 DOM?多个空格仅显示为一个,除非您使用 <pre>white-space: pre;或类似的东西,所以看起来结果被 trim 到只有一个空格。

关于javascript - 模板文字和无括号函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65747477/

相关文章:

javascript - 宿主元素的条件样式

javascript - 我如何使用 jQuery 动态翻译 html 输入占位符?

javascript - 有没有办法排除以某些值开头的字符串?

javascript - 带有 es6-promified 对象的 sinon stub

javascript - 如何检测何时在 javascript 中设置了全局变量?

javascript - 我正在尝试使用模板文字在 html 中显示来自 javascript 的文本,但元素未定义,我该怎么办?

javascript - Chrome 开发工具的性能分析结果中的监听器

javascript - jquery val 与实际值不同

javascript - 在没有模板化表达式的情况下使用 ES6 模板文字语法有缺点吗?

javascript - 使用 JavaScript 模板文字输出 CSS 中背景属性的值