我有一个赋值,后跟一个字符串插值:
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/