operator-assignment

尽可能要求或禁止赋值运算符简写

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行选项自动修复

JavaScript 提供了结合变量赋值和一些简单数学运算的速记运算符。例如,x = x + 4 可以缩短为 x += 4。支持的速记形式如下:

¥JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, x = x + 4 can be shortened to x += 4. The supported shorthand forms are as follows:

 Shorthand | Separate
-----------|------------
 x += y    | x = x + y
 x -= y    | x = x - y
 x *= y    | x = x * y
 x /= y    | x = x / y
 x %= y    | x = x % y
 x **= y   | x = x ** y
 x <<= y   | x = x << y
 x >>= y   | x = x >> y
 x >>>= y  | x = x >>> y
 x &= y    | x = x & y
 x ^= y    | x = x ^ y
 x |= y    | x = x | y

规则详情

¥Rule Details

此规则在可能的情况下要求或禁止赋值运算符简写。

¥This rule requires or disallows assignment operator shorthand where possible.

该规则适用于上表中列出的运算符。它不报告逻辑赋值运算符 &&=||=??=,因为它们的短路行为与其他赋值运算符不同。

¥The rule applies to the operators listed in the above table. It does not report the logical assignment operators &&=, ||=, and ??= because their short-circuiting behavior is different from the other assignment operators.

选项

¥Options

此规则有一个字符串选项:

¥This rule has a single string option:

  • "always"(默认)需要尽可能使用赋值运算符简写

    ¥"always" (default) requires assignment operator shorthand where possible

  • "never" 不允许赋值运算符简写

    ¥"never" disallows assignment operator shorthand

always

使用默认 "always" 选项的此规则的错误代码示例:

¥Examples of incorrect code for this rule with the default "always" option:

在线运行
/*eslint operator-assignment: ["error", "always"]*/

x = x + y;
x = y * x;
x[0] = x[0] / y;
x.y = x.y << z;

使用默认 "always" 选项的此规则的正确代码示例:

¥Examples of correct code for this rule with the default "always" option:

在线运行
/*eslint operator-assignment: ["error", "always"]*/

x = y;
x += y;
x = y * z;
x = (x * y) * z;
x[0] /= y;
x[foo()] = x[foo()] % 2;
x = y + x; // `+` is not always commutative (e.g. x = "abc")

never

使用 "never" 选项的此规则的错误代码示例:

¥Examples of incorrect code for this rule with the "never" option:

在线运行
/*eslint operator-assignment: ["error", "never"]*/

x *= y;
x ^= (y + z) / foo();

使用 "never" 选项的此规则的正确代码示例:

¥Examples of correct code for this rule with the "never" option:

在线运行
/*eslint operator-assignment: ["error", "never"]*/

x = x + y;
x.y = x.y / a.b;

何时不使用

¥When Not To Use It

使用运算符分配简写是一种风格选择。关闭此规则将允许开发者根据具体情况选择哪种样式更具可读性。

¥Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis.

版本

此规则是在 ESLint v0.10.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号