# eqeqeq
需要使用 === 和 !==
一些该规则报告的问题可以通过 --fix 命令行选项 自动修复
使用类型安全的相等运算符 === 和 !== 而不是它们的常规对应项 == 和 != 被认为是一种很好的做法。
原因是 == 和 != 在相当晦涩的 抽象等式比较算法 之后进行类型强制。例如,以下语句都被视为 true:
[] == false[] == ![]3 == "03"
如果其中一个出现在诸如 a == b 之类的看似无辜的声明中,则很难发现实际问题。
# 规则详情
此规则旨在消除类型不安全的相等运算符。
此规则的错误代码示例:
/*eslint eqeqeq: "error"*/
if (x == 42) { }
if ("" == text) { }
if (obj.getStuff() != undefined) { }
命令行中的 --fix 选项会自动修复此规则报告的一些问题。只有当其中一个操作数是 typeof 表达式,或者两个操作数都是具有相同类型的字面时,才会解决问题。
# 选项
# always
"always" 选项(默认)强制在每种情况下使用 === 和 !==(除非您选择更具体地处理 null [见下文])。
"always" 选项的错误代码示例:
/*eslint eqeqeq: ["error", "always"]*/
a == b
foo == true
bananas != 1
value == undefined
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null
"always" 选项的正确代码示例:
/*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" 选项的错误代码示例:
/*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" 选项的正确代码示例:
/*eslint eqeqeq: ["error", "smart"]*/
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null
# allow-null
**已弃用:**不要使用此选项,而是使用 "always" 并传递值为 "ignore" 的 "null" 选项属性。这将告诉 ESLint 始终强制执行严格相等,除非与 null 字面进行比较。
["error", "always", {"null": "ignore"}]
# 何时不使用
如果您不想强制使用相等运算符的样式,那么禁用此规则是安全的。