我需要存储点列表并检查该列表中是否已包含新点
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
}
显然 typescript 使用引用比较,但在这种情况下没有意义。在 Java 或 C# 中,我会重载 equals
方法,在 typescript 中这似乎是不可能的。
我考虑过使用 foreach
遍历数组并检查每个条目是否相等,但这看起来相当复杂并且会使代码膨胀。
typescript 中是否有类似 equals
的东西?我如何实现自己的比较?
最佳答案
Typescript 不会向 JavaScript 添加任何功能。它只是“类型化”和一些语法改进。
因此,没有一种方法可以用与您在 C# 中所做的等效的方式来覆盖 equals
。
但是,您最终可能会在 C# 中使用 Hash
或强类型的 Dictionary
进行高效查找(除了可能的数组之外),而不是使用“索引”函数。
为此,我建议您使用关联数组结构来存储 Point
。
你会做类似的事情:
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;
如果 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...
});
关于javascript - typescript :避免通过引用进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406384/