javascript - 赋值后需要分号,然后是 js 字符串插值

标签 javascript

我有一个赋值,后跟一个字符串插值:

var a = 3;
`${a} One two three`

"3 One two three"

如果我留下 ;赋值后代码无效:

var a = 3
`${a} One two three`

VM573:2 Uncaught TypeError: 3 is not a function
    at <anonymous>:2:1

我认为;仅在 {} 之后才是强制的... 有人可以解释一下上面的内容吗?

最佳答案

3 被解释为 template literal tag 。模板文字前面可以有一个“标签”,它是对函数的引用。例如:

function tag() {
  return 'other string';
}
const s = tag`some string`;
console.log(s); // 'other string'

在您的情况下,会引发错误,因为 3 不是函数。分号消除了数字的歧义,并使其被准确地解析为数字。

关于javascript - 赋值后需要分号,然后是 js 字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892057/

相关文章:

javascript - 如何在 html 中的 <links> href 路径中使用变量

javascript - 使用鼠标滚动实现无限图像

javascript - 带有url的页面加载的过渡效果

Javascript - <a href></a> 内部警报

javascript - 如何在 v-html 之间切换并在 vue.js 中以纯文本形式插入?

javascript - 试图将我的导航栏和汉堡包图标居中

javascript - 轻量级draggable jQuery,拖动屏幕

javascript div 关闭问题

javascript - 用于电子邮件验证的 firebase-ui

javascript - 是否可以导入文件夹中的所有文件?