no-unneeded-ternary
当存在更简单的替代方案时,禁用三元运算符
在 JavaScript 中,一个常见的错误是使用条件表达式在两个布尔值之间进行选择,而不是使用 !
将测试转换为布尔值。以下是一些例子
// Bad
const isYes = answer === 1 ? true : false;
// Good
const isYes = answer === 1;
// Bad
const isNo = answer === 1 ? false : true;
// Good
const isNo = answer !== 1;
另一个常见的错误是将单个变量同时用作条件测试和结果。在这种情况下,可以使用逻辑 OR
来提供相同的功能。这是一个例子
// Bad
foo(bar ? bar : 1);
// Good
foo(bar || 1);
规则详情
此规则禁止在存在更简单的替代方案时使用三元运算符。
此规则的错误代码示例
在 Playground 中打开
/*eslint no-unneeded-ternary: "error"*/
const a = ;
const b = ;
此规则的正确代码示例
在 Playground 中打开
/*eslint no-unneeded-ternary: "error"*/
const a = x === 2 ? "Yes" : "No";
const b = x !== false;
const c = x ? "Yes" : "No";
const d = x ? y : x;
f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.
选项
此规则具有对象选项
"defaultAssignment": true
(默认) 允许条件表达式作为默认赋值模式"defaultAssignment": false
禁止条件表达式作为默认赋值模式
defaultAssignment
当设置为 true
时(默认情况下是这样),defaultAssignment
选项允许 x ? x : expr
形式的表达式(其中 x
是任何标识符,expr
是任何表达式)。
使用 { "defaultAssignment": false }
选项时,此规则的其他错误代码示例
在 Playground 中打开
/*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/
const a = ;
f();
请注意,defaultAssignment: false
仍然允许 x ? expr : x
形式的表达式(其中标识符位于三元运算符的右侧)。
何时不使用它
如果您不关心条件表达式中不必要的复杂性,则可以关闭此规则。
相关规则
版本
此规则在 ESLint v0.21.0 中引入。