如何在javascript中执行小于/大于自定义对象的比较 [英] How to perform less than/greater than comparisons on custom objects in javascript

查看:58
本文介绍了如何在javascript中执行小于/大于自定义对象的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有几个成员的自定义类。我需要将它们相互比较。 javascript让我写:

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);
if (a < b) { ...

但我不明白逻辑比较的行为。有人可以解释<的语义。在上面的代码比较?有没有办法控制发生的事情,以便我能做出正确的行为?我知道我可以为这个类写一个比较方法,但是因为javascript让我写它,我想知道它在做什么。

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.

谢谢。

推荐答案

您需要定义一个返回可以使用的原语的 .valueOf 方法作比较:

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

如果你没有定义它,字符串[object Object]用于比较:

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

这篇关于如何在javascript中执行小于/大于自定义对象的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆