Typescript:避免通过引用进行比较

2023-12-27

我需要存储点列表并检查新点是否已包含在该列表中

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

window.onload = () => {
    var points : Point[] = [];
    points.push(new Point(1,1));
    var point = new Point(1,1);
    alert(points.indexOf(point)); // -1 
}

显然打字稿使用引用比较,但在这种情况下这是没有意义的。在 Java 或 C# 中我会重载equals方法,在打字稿中似乎不可能。

我考虑用循环遍历数组foreach并检查每个条目是否相等,但这看起来相当复杂并且会使代码变得臃肿。

有没有类似的东西equals在打字稿中?我如何实现自己的比较?


Typescript 不会向 JavaScript 添加任何功能。它只是“键入”和一些语法改进。

所以,没有办法覆盖equals与您在 C# 中所做的方式等效。

但是,您最终可能会使用Hash或强类型Dictionary在 C# 中进行有效的查找(除了可能的数组之外),而不是使用“索引”函数。

为此,我建议您使用关联数组结构来存储Points.

你会做类似的事情:

class Point {
    constructor(public x:Number = 0, 
        public y:Number = 0 ) {     
    }   
    public toIndexString(p:Point):String {
        return Point.pointToIndexString(p.x, p.y);  
    }       
    static pointToIndexString(x:Number, y:Number):String {
        return x.toString() + "@" + y.toString();   
    }       
}

var points:any = {};
var p: Point = new Point(5, 5);
points[p.toIndexString()] = p;

If a Point不存在,正在检查points将返回关联数组undefined.

包装数组的函数很简单:

function findPoint(x:Number, y:Number):Point {
    return points[Point.pointToIndexString(x, y)];
}

循环遍历所有点很容易:

// define the callback (similar in concept to defining delegate in C#)
interface PointCallback {
    (p:Point):void;
}

function allPoints(callback:PointCallback):void {
    for(var k in points) {
        callback(points[k]);
    }
}

allPoints((p) => {
   // do something with a Point...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript:避免通过引用进行比较 的相关文章

随机推荐