简体   繁体   English

如何在 javascript 中对自定义对象执行小于/大于比较

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

I have a custom class that has several members.我有一个包含多个成员的自定义类。 I need to compare them to each other.我需要将它们相互比较。 javascript lets me write: javascript让我写:

var a = new MyType(1);
var b = new MyType(2);
if (a < b) { ...

but I don't understand the behavior of the logical comparison.但我不明白逻辑比较的行为。 Can someone explain the semantics of the < comparison in the above code?有人能解释一下上面代码中 < 比较的语义吗? Is there a way to control what happens so that I can get right behavior?有没有办法控制发生的事情,以便我能够做出正确的行为? I know I can write a comparison method for the class, but since javascript lets me write it, I wondered what it thought it was doing.我知道我可以为该类编写一个比较方法,但是由于 javascript 允许我编写它,我想知道它认为它在做什么。

Thanks.谢谢。

You need to define a .valueOf method that returns a primitive that can be used for comparison:您需要定义一个.valueOf方法,该方法返回可用于比较的原语:

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]" < "[object Object]"
false
"[object Object]" > "[object Object]"
false
"[object Object]" >= "[object Object]"
true
"[object Object]" <= "[object Object]"
true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM