Index

no-eq-null

禁止在没有类型检查运算符的情况下进行 null 比较

与没有类型检查操作符(==!=)的 null 相比,可能会产生意想不到的结果,因为比较不仅在与 null 比较时会计算为 true,还会在与 undefined 值比较时计算为 true

🌐 Comparing to null without a type-checking operator (== or !=), can have unintended results as the comparison will evaluate to true when comparing to not just a null, but also an undefined value.

if (foo == null) {
  bar();
}

规则详情

🌐 Rule Details

no-eq-null 规则旨在通过确保对 null 的比较仅匹配 null 而不是 undefined,从而减少潜在的错误和不希望的行为。因此,当使用 ==!= 时,它会标记对 null 的比较。

🌐 The no-eq-null rule aims reduce potential bug and unwanted behavior by ensuring that comparisons to null only match null, and not also undefined. As such it will flag comparisons to null when using == and !=.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-eq-null: "error"*/

if (foo == null) {
  bar();
}

while (qux != null) {
  baz();
}

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-eq-null: "error"*/

if (foo === null) {
  bar();
}

while (qux !== null) {
  baz();
}

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 When Not To Use It

如果你想在一般情况下强制执行类型检查操作,请改用更强大的 eqeqeq

🌐 If you want to enforce type-checking operations in general, use the more powerful eqeqeq instead.

兼容性

🌐 Compatibility

  • JSHint:此规则对应于 JSHint 的 eqnull 规则。

版本

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

资源