Best and/or shortest way to do strict (non-type converting) <, >, <=, >= comparison in Javascript

前端 未结 2 1796
你的背包
你的背包 2020-12-30 21:18

In Javascript, the == comparison has a strict (non-type converting) version: ===. Likewise, != has the strict form !==. T

相关标签:
2条回答
  • 2020-12-30 22:03

    How about creating a Object and using it

    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)) ;   
    
    0 讨论(0)
  • 2020-12-30 22:06

    There are no built-in operators for what you want, but you can always create your own functions. For example, for <:

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

    Another option, if you're only dealing with strings and numbers, is extending String.prototype and 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
    
    0 讨论(0)
提交回复
热议问题