no-confusing-arrow
禁止使用可能与比较混淆的箭头函数
此规则报告的一些问题可通过 --fix
命令行选项自动修复
此规则在 ESLint v8.53.0 中已弃用。请在 @stylistic/eslint-plugin-js
中使用 相应的规则。
¥This rule was deprecated in ESLint v8.53.0. Please use the corresponding rule in @stylistic/eslint-plugin-js
.
箭头函数 (=>
) 在语法上类似于一些比较运算符(>
、<
、<=
和 >=
)。此规则警告不要在可能与比较运算符混淆的地方使用箭头函数语法。
¥Arrow functions (=>
) are similar in syntax to some comparison operators (>
, <
, <=
, and >=
). This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator.
这是一个示例,其中 =>
的用法可能会令人困惑:
¥Here’s an example where the usage of =>
could be confusing:
// The intent is not clear
var x = a => 1 ? 2 : 3;
// Did the author mean this
var x = function (a) {
return 1 ? 2 : 3;
};
// Or this
var x = a <= 1 ? 2 : 3;
规则详情
¥Rule Details
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-confusing-arrow: "error"*/
var x = a => 1 ? 2 : 3;
var x = (a) => 1 ? 2 : 3;
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-confusing-arrow: "error"*/
var x = a => (1 ? 2 : 3);
var x = (a) => (1 ? 2 : 3);
var x = (a) => {
return 1 ? 2 : 3;
};
var x = a => { return 1 ? 2 : 3; };
选项
¥Options
此规则接受两个具有以下默认值的选项参数:
¥This rule accepts two options argument with the following defaults:
{
"rules": {
"no-confusing-arrow": [
"error",
{ "allowParens": true, "onlyOneSimpleParam": false }
]
}
}
allowParens
是一个布尔设置,可以是 true
(默认)或 false
:
¥allowParens
is a boolean setting that can be true
(default) or false
:
-
true
放宽了规则并接受括号作为有效的 “confusion-preventing” 语法。¥
true
relaxes the rule and accepts parenthesis as a valid “confusion-preventing” syntax. -
即使表达式用括号括起来,
false
也会触发警告¥
false
warns even if the expression is wrapped in parenthesis
使用 {"allowParens": false}
选项的此规则的错误代码示例:
¥Examples of incorrect code for this rule with the {"allowParens": false}
option:
/*eslint no-confusing-arrow: ["error", {"allowParens": false}]*/
var x = a => (1 ? 2 : 3);
var x = (a) => (1 ? 2 : 3);
onlyOneSimpleParam
是一个布尔设置,可以是 true
或 false
(默认):
¥onlyOneSimpleParam
is a boolean setting that can be true
or false
(default):
-
true
放宽规则,如果箭头函数有 0 个或 1 个以上的参数,或者参数不是标识符,则不报错。¥
true
relaxes the rule and doesn’t report errors if the arrow function has 0 or more than 1 parameters, or the parameter is not an identifier. -
无论参数如何,
false
都会触发警告。¥
false
warns regardless of parameters.
使用 {"onlyOneSimpleParam": true}
选项的此规则的正确代码示例:
¥Examples of correct code for this rule with the {"onlyOneSimpleParam": true}
option:
/*eslint no-confusing-arrow: ["error", {"onlyOneSimpleParam": true}]*/
() => 1 ? 2 : 3;
(a, b) => 1 ? 2 : 3;
(a = b) => 1 ? 2 : 3;
({ a }) => 1 ? 2 : 3;
([a]) => 1 ? 2 : 3;
(...a) => 1 ? 2 : 3;
相关规则
版本
此规则是在 ESLint v2.0.0-alpha-2 中引入。