27

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比較演算子

4

2 に答える 2

12

必要な組み込み演算子はありませんが、いつでも独自の関数を作成できます。たとえば、次の場合<:

function lt(o1, o2) {
    return ((typeof o1 === typeof o2) && (o1 < o2));
}
lt("10", 11); // false

文字列と数値のみを扱う場合の別のオプションは、 and を拡張することString.prototypeですNumber.prototype

function lt(o) {
    return ((typeof this.valueOf() === typeof o) && (this < o));
}
String.prototype.lt = lt;
Number.prototype.lt = lt;
"10".lt(11);   // false
(11).lt("12"); // false
于 2012-10-26T17:00:42.977 に答える
7

オブジェクトを作成して使用するのはどうですか

var strictComparison = {
    "<" : function(a,b) { return ((typeof a === typeof b) && (a < b)) },
    "<=" : function(a,b) { return ((typeof a === typeof b) && (a <= b)) },
    ">" : function(a,b) { return ((typeof a === typeof b) && (a > b)) },
    ">=" : function(a,b) { return ((typeof a === typeof b) && (a >= b)) }
};

console.log(strictComparison["<"](5,"6")) ;  
console.log(strictComparison[">"](5,6)) ;   
于 2012-10-26T17:03:27.263 に答える