no-unexpected-multiline
禁止混淆多行表达式
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
在 JavaScript 中,分号通常是可选的,因为有自动分号插入(ASI)。你可以使用 semi 规则来要求或禁止分号。
🌐 Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the semi rule.
ASI 的规则相对简单:正如 Isaac Schlueter 曾描述的,换行符总是结束一个语句,就像分号一样,除非以下情况之一成立:
🌐 The rules for ASI are relatively straightforward: As once described by Isaac Schlueter, a newline character always ends a statement, just like a semicolon, except where one of the following is true:
- 该语句有未闭合的括号、数组字面量或对象字面量,或者以其他不是有效语句结束方式的方式结束。(例如,以
.或,结尾。) - 这一行是
--或++(在这种情况下,它将递减/递增下一个标记。) - 它是一个
for()、while()、do、if()或else,并且没有{ - 下一行以
[、(、+、*、/、-、,、.开头,或者以某个只能出现在单个表达式中两个标记之间的其他二元运算符开头。
在换行符不结束语句的例外情况下,因打字错误而省略分号会导致两个无关的连续行被解释为一个表达式。尤其是在没有分号的编码风格中,读者可能会忽略这个错误。虽然在语法上是正确的,但代码在执行时可能会抛出异常。
🌐 In the exceptions where a newline does not end a statement, a typing mistake to omit a semicolon causes two unrelated consecutive lines to be interpreted as one expression. Especially for a coding style without semicolons, readers might overlook the mistake. Although syntactically correct, the code might throw exceptions when it is executed.
规则详情
🌐 Rule Details
此规则不允许混淆多行表达式,其中换行符看起来像是在结束语句,但不是。
🌐 This rule disallows confusing multiline expressions where a newline looks like it is ending a statement, but is not.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-unexpected-multiline: "error"*/
const foo = bar
(1 || 2).baz();
const hello = 'world'
[1, 2, 3].forEach(addNumber);
const x = function() {}
`hello`
const y = function() {}
y
`hello`
const z = foo
/regex/g.test(bar)
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-unexpected-multiline: "error"*/
const foo = bar;
(1 || 2).baz();
const baz = bar
;(1 || 2).baz()
const hello = 'world';
[1, 2, 3].forEach(addNumber);
const hi = 'world'
void [1, 2, 3].forEach(addNumber);
const x = function() {};
`hello`
const tag = function() {}
tag `hello`
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
如果你确信不会意外引入这样的代码,则可以关闭此规则。
🌐 You can turn this rule off if you are confident that you will not accidentally introduce code like this.
请注意,被认为有问题的模式不会被 semi 规则标记。
🌐 Note that the patterns considered problems are not flagged by the semi rule.
相关规则
版本
此规则是在 ESLint v0.24.0 中引入。