ES6模板字符串和自动分号插入

ES6模板字符串和自动分号插入

本文介绍了ES6模板字符串和自动分号插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

`abc`.split(`b`)
`abc`.split(`b`)

使用 TypeError:abc失败。 split(...)不是一个函数

为了使其工作,我们需要在这两个语句之间插入一个分号。
如果我们在第二行使用一个常规的字符串,代码也可以正常工作:

To make it work, we need to insert a semicolon between those two statements.Also the code works fine if we use a regular string on the second line:

`abc`.split(`b`)
"abc".split(`b`)

这个行为的原因是什么?

What is the reason for this behaviour?

我想这与自动分号插入做一些棘手的事情有关,但我不知道这是什么。 br>
此外,常规和模板字符串之间似乎有区别的事实有点让我感到困惑。不应该等于吗?

I guess it has something to do with the automatic semicolon insertion doing some whacky stuff, but I can't figure out what this would be.
Also the fact that there seems to be a difference between regular and template strings kinda confuses me. Shouldn't those be equivalent?

推荐答案

模板文字可以是,字符串文字不能。请注意,

Template literals can be tagged with a function, string literals cannot. Notice that

tag`a ${x} b`;

基本相当于

tag("a ", x, " b");

由于您的表达式`abc`.split(`b`)`abc `.split(`b`)在语法上有效,发生在这里。不要在必要的地方省略分号。这不是说ASI正在做一些重要的事情,只是在你期望的时候什么都不做。

Since your expression `abc`.split(`b`) `abc`.split(`b`) is grammatically valid, there is no automatic semicolon insertion happening here. Don't omit the semicolons where they are necessary. It's not that ASI is doing whacky stuff, it's just doing nothing while you expect it to.

如果你想省略分号,让它们自动插入到可能的地方,您将中放一个以 [ / + - `

If you want to omit semicolons and let them be automatically inserted where ever possible, you will need to put one at the begin of every line that starts with (, [, /, +, - or `.

这篇关于ES6模板字符串和自动分号插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:35