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"}]
何時不使用它
如果您不想強制執行使用等號運算子的樣式,則可以安全地停用此規則。
版本
此規則是在 ESLint v0.0.2 中引入的。