打字稿:避免通过引用进行比较 [英] Typescript: Avoid comparison by reference

查看:135
本文介绍了打字稿:避免通过引用进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to store a list of points and check if a new point is already included in that list

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中似乎不可能。

Obviously typescript uses comparison by reference but in this case that doesn't make sense. In Java or C# I would overload the equals method, in typescript that doesn't seem to be possible.

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

I considered to loop through the array with foreach and check each entry for equality, but that seems rather complicated and would bloat the code.

在typescript中是否有类似 equals 的东西?

Is there something like equals in typescript ? How can I implement my own comparisons ?

推荐答案

您可以将集合包装在 PointList 只允许通过添加方法添加对象,该方法检查以确保没有重复项

You could wrap the collection in a PointList that only allows Point objects to be added via an add method, which checks to ensure no duplicates are added.

这有利于在一个地方封装无重复规则,而不是希望所有调用代码在添加副本之前检查在许多地方复制规则。

This has the benefit of encapsulating the "No duplicates" rule in a single place, rather than hoping that all calling code will check before adding a duplicate, which would duplicate the rule in many places.

class Point {
    constructor(public x: number, public y: number) {
    }
}

class PointList {
    private points: Point[] = [];

    get length() {
        return this.points.length;
    }

    add(point: Point) {
        if (this.exists(point)) {
            // throw 'Duplicate point';
            return false;
        }

        this.points.push(point);
        return true;
    }

    exists(point: Point) {
        return this.findIndex(point) > -1;
    }

    findIndex(point: Point) {
        for (var i = 0; i < this.points.length; i++) {
            var existingPoint = this.points[i];
            if (existingPoint.x === point.x && existingPoint.y === point.y) {
                return i;
            }
        }

        return -1;
    }
}

var pointList = new PointList();

var pointA = new Point(1, 1);
var pointB = new Point(1, 1);
var pointC = new Point(1, 2);

pointList.add(pointA);
alert(pointList.length); // 1

pointList.add(pointB);
alert(pointList.length); // 1

pointList.add(pointC);
alert(pointList.length); // 2

这篇关于打字稿:避免通过引用进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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