網站搜尋

javascript - typescript 如何比較兩個物件?


我有一個名為 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;
        }
    }

當我創建這個類的兩個不同對象時

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

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

當我使用 a1 === a2 時,它應該返回 true。我需要在我的類中做哪些更改才能使 a1 === a2?我在稅務類中需要做什麼?或者我需要覆寫稅務類中的哪個方法?

答案#1

你正在比較同一個類別的兩個不同實例。即使實例中的值相同,它們仍然是完全獨立的兩個實體。

例如,如果我們有一個具有單一屬性 name 的 People 類。即使世界上有兩個人叫做 John Smith,他們仍然是完全不同的兩個人。

每個實例都有其獨特的識別碼。

如果你想檢查兩個稅是否有完全相同的數值,你可以一個一個地檢查它們。

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

更多關於比較物件的資訊可以在這裡找到