JavaScript 中是否有任何类型的哈希码函数? [英] Is there any kind of hash code function in JavaScript?

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

问题描述

基本上,我正在尝试创建一个由独特对象组成的对象,一个集合.我有一个绝妙的主意,就是将 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 函数.- olliej

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.

这篇关于JavaScript 中是否有任何类型的哈希码函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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