使分号规则简单
以(,[,',或任何算术运算符开头的每一行,如果您希望它被解释为自己的行,必须以分号开头~否则,它可能会意外地与前一行合并。所有其他换行符都有隐式分号。
就是这样。完成了。
Note that /, +, - are the only valid operators you would want to do this for anyway. You would never want a line to begin with '*', since it's a binary operator that could never make sense at the beginning of a line.
You should put the semicolons at the start of the line when doing this. You should not try to "fix" the issue by adding a semicolon to the previous line, or any reordering or moving of the code will cause the issue to potentially manifest again. Many of the other answers (including top answers) make this suggestion, but it's not a good practice.
为什么这些特殊的字符需要开头的分号?
考虑以下几点:
func()
;[0].concat(myarr).forEach(func)
;(myarr).forEach(func)
;`hello`.forEach(func)
;/hello/.exec(str)
;+0
;-0
通过遵循给定的规则,可以防止上面的代码被重新解释为
func()[0].concat(myarr).forEach(func)(myarr).forEach(func)`hello`.forEach(func)/hello/.forEach(func)+0-0
额外的笔记
说明一下会发生什么:括号将被用作索引,圆括号将被视为函数参数。反撇号将转换为带标记的模板,regex将转换为除法,显式的+/-符号整数将转换为正负运算符。
当然,您可以通过在每个换行符的末尾添加分号来避免这种情况,但不要相信这样做可以让您像C程序员一样编写代码。由于仍然存在这样的情况,即当您不使用分号结束一行时,Javascript可能会隐式地代替您添加一个分号。记住这样的语句
return // Implicit semicolon, will return undefined.
(1+2);
i // Implicit semicolon on this line
++; // But, if you really intended "i++;"
// and you actually wrote it like this,
// you need help.
上面的情况会发生return/continue/break/++/——。任何linter都会捕捉到带有死代码的前一种情况,或者带有++/——语法错误的后一种情况。
最后,如果您希望文件连接工作,请确保每个文件以分号结束。如果您正在使用捆绑程序(推荐),它应该自动执行此操作。