no-unneeded-ternary

当存在更简单的替代方案时,禁止使用三元运算符

🔧 Fixable

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

JavaScript 中的一个常见错误是使用条件表达式在两个布尔值之间进行选择,而不是使用 ! 将测试转换为布尔值。这里有些例子:

¥It’s a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean. Here are some examples:

// Bad
var isYes = answer === 1 ? true : false;

// Good
var isYes = answer === 1;

// Bad
var isNo = answer === 1 ? false : true;

// Good
var isNo = answer !== 1;

另一个常见的错误是使用单个变量作为条件测试和结果。在这种情况下,逻辑 OR 可用于提供相同的功能。这是一个例子:

¥Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical OR can be used to provide the same functionality. Here is an example:

// Bad
foo(bar ? bar : 1);

// Good
foo(bar || 1);

规则详情

¥Rule Details

当存在更简单的替代方案时,此规则不允许三元运算符。

¥This rule disallow ternary operators when simpler alternatives exist.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-unneeded-ternary: "error"*/

var a = x === 2 ? true : false;

var a = x ? true : false;

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-unneeded-ternary: "error"*/

var a = x === 2 ? "Yes" : "No";

var a = x !== false;

var a = x ? "Yes" : "No";

var a = x ? y : x;

f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.

选项

¥Options

此规则有一个对象选项:

¥This rule has an object option:

  • "defaultAssignment": true(默认)允许条件表达式作为默认赋值模式

    ¥"defaultAssignment": true (default) allows the conditional expression as a default assignment pattern

  • "defaultAssignment": false 不允许将条件表达式作为默认赋值模式

    ¥"defaultAssignment": false disallows the conditional expression as a default assignment pattern

defaultAssignment

当设置为 true(默认情况下)时,defaultAssignment 选项允许 x ? x : expr 形式的表达式(其中 x 是任何标识符,expr 是任何表达式)。

¥When set to true, which it is by default, The defaultAssignment option allows expressions of the form x ? x : expr (where x is any identifier and expr is any expression).

使用 { "defaultAssignment": false } 选项的此规则的其他错误代码示例:

¥Examples of additional incorrect code for this rule with the { "defaultAssignment": false } option:

在线运行
/*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/

var a = x ? x : 1;

f(x ? x : 1);

请注意,defaultAssignment: false 仍然允许 x ? expr : x 形式的表达式(其中标识符位于三元组的右侧)。

¥Note that defaultAssignment: false still allows expressions of the form x ? expr : x (where the identifier is on the right hand side of the ternary).

何时不使用

¥When Not To Use It

如果你不关心条件表达式中不必要的复杂性,你可以关闭此规则。

¥You can turn this rule off if you are not concerned with unnecessary complexity in conditional expressions.

版本

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

资源

ESLint 中文网
粤ICP备13048890号