Javascript では、==
比較には厳密な (型変換を行わない) バージョンがあります: ===
. 同様に、!=
has は厳密な形式!==
です。これらは、次の狂気からあなたを守ります。
var s1 = "1",
i1 = 1,
i2 = 2;
(s1 == i1) // true, type conversion
(s1 != i1) // false, type conversion
(s1 === i1) // false, no type conversion
(s1 !== i1) // true, no type conversion
ただし、他の比較演算子には同等の厳格モードはありません。
(s1 < i2) // true, type conversion
(s1 <= i2) // true, type conversion
([] < i2) // true, wait ... wat!?
明白な解決策はかなり冗長に思えます:
((typeof s1 === typeof i2) && (s1 < i2)) // false
Javascriptでこれを行うためのより慣用的な(または冗長でない)方法はありますか?
リファレンス: MDN比較演算子