JavaScript中是否有任何类型的哈希码函数?

2022-01-17 00:00:00 set hash javascript hashcode

基本上,我正在尝试创建一个由唯一对象组成的对象,一个集合.我有一个绝妙的想法,就是使用带有对象作为属性名称的 JavaScript 对象.比如,

Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

set[obj] = true;

这在一定程度上可行.它适用于字符串和数字,但对于其他对象,它们似乎都散列"到相同的值并访问相同的属性.有什么方法可以为对象生成唯一的哈希值吗?字符串和数字是怎么做的,我可以覆盖相同的行为吗?

This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?

推荐答案

JavaScript 对象只能使用字符串作为键(其他任何东西都转换为字符串).

JavaScript objects can only use strings as keys (anything else is converted to a string).

您也可以维护一个数组来索引相关对象,并将其索引字符串用作对该对象的引用.像这样的:

You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:

var ObjectReference = [];
ObjectReference.push(obj);

set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;

显然这有点冗长,但您可以编写几个方法来处理它,并随意获取和设置所有内容.

Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.

您的猜测是事实——这是 JavaScript 中定义的行为——特别是发生了 toString 转换,这意味着您可以在将用作属性名称的对象上定义自己的 toString 函数.- 奥利耶

Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej

这带来了另一个有趣的点;您可以在要散列的对象上定义一个 toString 方法,这可以形成它们的散列标识符.

This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.

相关文章