Javascript 打字稿如何比较两个对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43634154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:03:43  来源:igfitidea点击:

how typescript comparing two objects?

javascripttypescript

提问by vishvas chauhan

I have one class called tax.

我有一门课叫tax.

    export class tax {
        private _id: string;
        private _name: string;
        private _percentage: number;`

        constructor(id: string = "", taxName: string = "", percentage: number = 0) {
            this._id = id;
            this._name = taxName;
            this._percentage = percentage;
        }


        public get id(): string {
            return this._id;
        }

        public set id(v: string) {
            this._id = v;
        }
        public get name(): string {
            return this._name;
        }

        public set name(v: string) {
            this._name = v;
        }
        public get percentage(): number {
            return this._percentage;
        }

        public set percentage(v: number) {
            this._percentage = v;
        }

        toString(){
            return this.id;
        }
    }

When I create 2 different objects of this class

当我创建此类的 2 个不同对象时

    a1: tax = new tax("id","name",4);
    a2: tax = new tax("id","name",4); 

    console.log(a1 === a2); //false
    console.log(a1 == a2); //false

When I give a1 === a2 it should give true. what changesi have to do in my class so it will give a1 === a2 ? What I have to do in tax class? or which method I have to override in tax class?

当我给出 a1 === a2 时,它应该给出 true。我必须在我的班级中做哪些改变,才能得到 a1 === a2 ?我必须在税务课上做什么?或者我必须在税类中覆盖哪种方法?

回答by Toby Mellor

You're comparing two different instances of the same class. Even though the values are the same within the instance, they're two completely separate entities.

您正在比较同一类的两个不同实例。即使实例中的值相同,它们也是两个完全独立的实体。

For example, if we were to have a Peopleclass with a single attribute name. Even if there are two people in the world called John Smith, they're two completely separate people.

例如,如果我们有一个People具有单个属性的类name。就算世界上有两个人叫作John Smith,也是完全不同的两个人。

Each instance has its own unique identifier.

每个实例都有自己的唯一标识符。

If you want to check if two taxes have the exact same values, you could check them one by one.

如果您想检查两种税是否具有完全相同的值,您可以一一检查它们。

console.log(a1.getId() === a2.getId() && a1.getName() === a2.getName() && a1.getPercentage() === a2.getPercentage()) // true

More information about comparing objects can be found here

可以在此处找到有关比较对象的更多信息