JavaScript中是否有任何一种哈希码功能? [英] Is there any kind of hash code function in JavaScript?
问题描述
set [obj] = true;
这可以起到一定的作用。它对字符串和数字非常有用,但对于其他对象,它们似乎都散列到相同的值并访问相同的属性。有什么方法可以为对象生成唯一的哈希值?字符串和数字如何做,我可以重写相同的行为吗?
解决方案JavaScript对象只能使用字符串作为键否则会转换为字符串)。
您也可以维护一个索引所讨论对象的数组,并使用索引字符串作为对象的引用。像这样:
var ObjectReference = [];
ObjectReference.push(obj);
set ['ObjectReference。'+ ObjectReference.indexOf(obj)] = true;
显然它有点冗长,但您可以编写几个方法来处理它并获取并设置所有这些都是可怜的。
编辑:
你的猜测是事实 - 是在JavaScript中定义的行为 - 特别是发生toString转换,这意味着您可以在将用作属性名称的对象上定义自己的toString函数。 - olliej
这提出了另一个有趣的观点;你可以在你想要散列的对象上定义一个toString方法,并且可以形成它们的散列标识符。
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 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.
Edit:
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
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.
这篇关于JavaScript中是否有任何一种哈希码功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!