How to perform less than/greater than comparisons on custom objects in javascript

前端 未结 1 1603
野性不改
野性不改 2020-12-09 03:29

I have a custom class that has several members. I need to compare them to each other. javascript lets me write:

var a = new MyType(1);
var b = new MyType(2);         


        
1条回答
  •  囚心锁ツ
    2020-12-09 04:20

    You need to define a .valueOf method that returns a primitive that can be used for comparison:

    function MyType( value ){
        this.value = value;
    }
    
    MyType.prototype.valueOf = function() {
        return this.value;
    };
    
    var a = new MyType(3),
        b = new MyType(5);
    
    a < b
    true
    a > b
    false
    a >= b
    false
    b < a
    false
    b > a
    true
    

    If you don't define it, the the string "[object Object]" is used for comparison:

    "[object Object]" < "[object Object]"
    false
    "[object Object]" > "[object Object]"
    false
    "[object Object]" >= "[object Object]"
    true
    "[object Object]" <= "[object Object]"
    true
    

    0 讨论(0)
提交回复
热议问题