版本

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" 選項,並傳遞值為 "ignore""null" 選項屬性。這會告知 ESLint 始終強制執行嚴格相等,除非與 null 字面值進行比較。

["error", "always", {"null": "ignore"}]

何時不該使用

如果您不想強制執行使用相等運算子的風格,那麼停用此規則是安全的。

版本

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

資源

變更語言