javascript - typescript :避免通过引用进行比较

标签 javascript web reference comparison typescript

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

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/

相关文章:

javascript - dart:如何动态传输数据?

c++ - 基于签名的 C++ 搜索

javascript - 如何限制定期向其中添加消息的 DIV 中的文本量?

javascript - 从 AngularJS 中的对象访问所有嵌套值的最快方法

javascript - 由于表单未连接而取消表单提交

seo - 什么是断开的相对链接?

javascript - 停止 JS 代码中的 getClientId() 计算

javascript - 使用数据库中的图像填充 dropzone.js 问题删除图像

c++ - 在定义明确的 C++ 中,从引用中获取的指针是否可以为空?

java - Java 中每个共享引用是否占用另一个内存字(例如 32 或 64 位)?