我找不到更多相关信息,但据我了解 has
方法来自Map
和Set
集合通过检查引用相等性来确定给定映射或集合是否具有对象。但我想通过比较对象的属性来检查它们是否相等。
例如:
let map = new Map();
let obj = {name: "Jack"};
map.set(obj, "myObj");
let result = map.has({name: "Jack"}); //false
result
是 false 但对象的属性是相同的,所以在这种情况下我想要 has
返回 true。
在 Java 中,我必须重写 equals
和hashCode
我的类中的方法来实现此类功能。我可以在 Javascript 中执行类似的操作而不覆盖 has
本身?
最佳答案
but the properties of the objects are identical
真的吗?如this answer概述,定义对象的身份通常非常困难,因为它是由不仅仅是简单的键值对构建的。因此,不可能派生出唯一的哈希值以用于哈希表,这就是 javascript 使用哈希表中的对象引用的原因。这也是有道理的,否则可能会发生碰撞。此外,如果您更改哈希表中包含的一个对象,使其等于另一个对象,那么会发生什么?
现在,在很多情况下,您可能知道对象是如何构建的以及如何获取其标识。想象一个拥有唯一用户名的玩家,例如:
function Player(username, password) {
this.username = username;
this.password = password
}
现在,当我们想要构建一个 Set 来检查用户名是否已存在时,仅使用 Players 用户名而不是玩家本身是有意义的:
const a = new Player("a", "super secret");
const b = new Player("b", "****");
new Set([a.username, b.username]);
或者您可以定义一种从玩家属性构建唯一 key 的方法:
Player.prototype.identity = function() {
return this.username + "°" + this.password;
};
所以人们可以这样做:
const a = new Player("this is", "equal");
const b = new Player("this is", "equal");
console.log(
a === b, // false
a.identity() === b.identity() // true
);
const players = new Set([a.identity()]);
players.has(b.identity()); // true
关于javascript - 如何确保 `has` 或 `Map` javascript 集合的 `Set` 方法按属性值比较对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50086258/