散列JavaScript对象 [英] Hashing JavaScript objects

查看:137
本文介绍了散列JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收JS对象列表作为参数的函数。我需要将这些对象的信息存储在私有变量中以供将来参考。我不想将一个属性填充到对象本身中,我只是想在字典中将它保留在带外。我需要能够在子线性时间内查找对象的元数据。为此,我需要一个 hash 函数,以便对于任何两个对象 o1 o2



hash(o1)!==每当 o1!== o2



完美的例子这样的哈希函数将是该对象的内存地址,但我不认为JS公开这一点。有没有办法?

解决方案

要存储关于对象的元数据,可以使用 WeakMap


WeakMaps是键/值映射,其中键是对象。






<请注意,此API仍处于试验阶段,因此尚未得到广泛支持(请参阅支持表)。有一个使用 defineProperty polyfill实现 >设置GUID(详情请参阅此处)。


I have a function that receives a list of JS objects as an argument. I need to store information about those objects in a private variable for future reference. I do not want to stuff a property into the objects themselves, I just want to keep it out of band in a dictionary. I need to be able to lookup metadata for an object in sub-linear time.

For this I need a hash function such that, for any two objects o1 and o2,

hash(o1) !== hash(o2) whenever o1 !== o2.

A perfect example of such a hash function would be the memory address of the object, but I don't think JS exposes that. Is there a way?

解决方案

To store metadata about objects, you can use an WeakMap:

WeakMaps are key/value maps in which keys are objects.


Note that this API is still experimental and thus not widely supported yet (see support table). There is a polyfill implementation which makes use of defineProperty to set GUIDs (see details here).

这篇关于散列JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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