版本

no-eq-null

禁止在未使用型別檢查運算子下比較 null

在未使用型別檢查運算子 (==!=) 的情況下與 null 進行比較,可能會產生非預期的結果,因為當與不僅是 null,還有 undefined 值進行比較時,比較結果也會評估為 true。

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

規則詳細資訊

no-eq-null 規則旨在透過確保與 null 的比較僅比對 null,而不比對 undefined,來減少潛在的錯誤和不必要的行為。 因此,當使用 ==!= 時,它會標記與 null 的比較。

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-eq-null: "error"*/

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

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

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-eq-null: "error"*/

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

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

何時不該使用

如果您想要全面強制執行型別檢查運算,請改用更強大的 eqeqeq

相容性

  • JSHint:此規則對應於 JSHint 的 eqnull 規則。

版本

此規則在 ESLint v0.0.9 中引入。

資源

變更語言