operator-assignment
尽可能要求或禁止赋值运算符简写
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"(默认)在可能的情况下需要使用赋值运算符简写"never"不允许使用赋值运算符简写
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 中引入。