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

Is there any kind of hash code function in JavaScript?(JavaScript中是否有任何类型的哈希码函数?)
本文介绍了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 函数.- 奥利耶

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中是否有任何类型的哈希码函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)