eqeqeq
要求使用 ===
和 !==
🔧 可修复
此规则报告的某些问题可以通过 --fix
命令行 选项自动修复
通常认为最佳实践是使用类型安全的相等运算符 ===
和 !==
,而不是其常规对应项 ==
和 !=
。
原因是 ==
和 !=
会进行类型强制转换,这种转换遵循相当晦涩的 抽象相等比较算法。例如,以下语句都被认为是 true
[] == false
[] == ![]
3 == "03"
如果其中一种情况发生在看似无辜的语句(如 a == b
)中,则实际问题很难被发现。
规则详情
此规则旨在消除类型不安全的相等运算符。
此规则的 错误 代码示例
在 Playground 中打开
/*eslint eqeqeq: "error"*/
if (x 42) { }
if ("" text) { }
if (obj.getStuff() undefined) { }
命令行中的 --fix
选项会自动修复此规则报告的某些问题。只有当其中一个操作数是 typeof
表达式,或者两个操作数都是相同类型的字面量时,问题才会被修复。
选项
always
"always"
选项(默认)强制在所有情况下使用 ===
和 !==
(除非您选择更具体地处理 null
[见下文])。
"always"
选项的 错误 代码示例
在 Playground 中打开
/*eslint eqeqeq: ["error", "always"]*/
a b
foo true
bananas 1
value undefined
typeof foo 'undefined'
'hello' 'world'
0 0
true true
foo null
"always"
选项的 正确 代码示例
在 Playground 中打开
/*eslint eqeqeq: ["error", "always"]*/
a === b
foo === true
bananas !== 1
value === undefined
typeof foo === 'undefined'
'hello' !== 'world'
0 === 0
true === true
foo === null
此规则可以选择接受第二个参数,该参数应该是一个对象,包含以下支持的属性
"null"
:自定义此规则如何处理null
字面量。可能的值always
(默认)- 始终使用===
或!==
。never
- 永远不要将===
或!==
与null
一起使用。ignore
- 不对此规则应用于null
。
smart
"smart"
选项强制使用 ===
和 !==
,但以下情况除外
- 比较两个字面量值。
- 评估
typeof
的值。 - 与
null
比较。
"smart"
选项的 错误 代码示例
在 Playground 中打开
/*eslint eqeqeq: ["error", "smart"]*/
// comparing two variables requires ===
a b
// only one side is a literal
foo true
bananas 1
// comparing to undefined requires ===
value undefined
"smart"
选项的 正确 代码示例
在 Playground 中打开
/*eslint eqeqeq: ["error", "smart"]*/
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null
allow-null
已弃用: 请使用 "always"
选项,并传递一个 "null"
选项属性,其值为 "ignore"
,而不是使用此选项。这将告诉 ESLint 始终强制执行严格相等,除非与 null
字面量进行比较。
["error", "always", {"null": "ignore"}]
何时不使用
如果您不想强制执行使用相等运算符的风格,那么禁用此规则是安全的。
版本
此规则在 ESLint v0.0.2 中引入。