但是对象的属性是相同的
真的吗?正如这个答案所概述的,通常很难定义对象的身份,因为它不仅仅是由单一的键值对构成的。因此,不可能为它派生一个唯一的散列以在散列表中使用,这就是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]);
或者您可以定义一种方法来从玩家属性中构建唯一键:
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