no-unexpected-multiline

禁止混淆多行表达式

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

由于自动分号插入 (ASI),分号在 JavaScript 中通常是可选的。你可以使用 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:

  • 该语句有一个未闭合的括号、数组字面量或对象字面量,或者以某种不是结束语句的有效方式的其他方式结束。(例如,以 ., 结尾。)

    ¥The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)

  • 该行是 --++(在这种情况下,它将递减/递增下一个令牌。)

    ¥The line is -- or ++ (in which case it will decrement/increment the next token.)

  • 它是 for()while()doif()else,且没有 {

    ¥It is a for(), while(), do, if(), or else, and there is no {

  • 下一行以 [(+*/-,. 或其他只能在单个表达式中的两个标记之间找到的二元运算符开头。

    ¥The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

在换行符未结束语句的例外情况下,省略分号的键入错误会导致两个不相关的连续行被解释为一个表达式。特别是对于没有分号的编码风格,读者可能会忽略这个错误。尽管语法正确,但代码在执行时可能会引发异常。

¥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"*/

var foo = bar
(1 || 2).baz();

var hello = 'world'
[1, 2, 3].forEach(addNumber);

let x = function() {}
`hello`

let y = function() {}
y
`hello`

let z = foo
/regex/g.test(bar)

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-unexpected-multiline: "error"*/

var foo = bar;
(1 || 2).baz();

var foo = bar
;(1 || 2).baz()

var hello = 'world';
[1, 2, 3].forEach(addNumber);

var hello = 'world'
void [1, 2, 3].forEach(addNumber);

let x = function() {};
`hello`

let tag = function() {}
tag `hello`

何时不使用

¥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 中引入。

资源

ESLint 中文网
粤ICP备13048890号