JavaScript中是否有任何一种哈希码功能? [英] Is there any kind of hash code function in JavaScript?

查看:76
本文介绍了JavaScript中是否有任何一种哈希码功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我试图创建一个唯一对象的集合。我有一个聪明的想法,就是使用一个带有对象属性名称的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆