在Javascript中,如何使用object作为hashmap的key?

In Javascript, how to use object as the key of a hashmap?

这是 REPL 中的结果

>>a1={1:2}
Object {1: 2}
>>a2={1:4}
Object {1: 4}
>>c={}
Object {}
>>c[a1]=2
2
>>c[a2]
2

可以看出,a1a2是不同的对象。但是,c[a1]c[a2] 会得到相同的结果。有没有办法使用对象作为哈希图的键?

您可以将对象转换为字符串。 javascript 对象中的键类型应该是字符串

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

你可以在上面找到相同的例子link。

c[<some_func_to_convert_obj_to_string(a1)>]=2

因此,如果您想将该对象用作键,您需要将该对象转换为唯一的字符串.. 这里有很多答案 Converting object to string。正如 Steven Wexler 指出 JSON.stringify 是不确定的,最好不要使用它。我不会再次复制这些功能,因为有一个专门的 SO 问题。

只有字符串可以用作对象键。您可以走 hacky 路线并使用 JSON.stringify() 将对象转换为字符串,但最好的选择是使用实际的哈希图。

您可以使用一个自定义实现,或者如果您的目标环境支持它,请使用 WeakMap

还有一个 WeakMap 填充程序,您可以在尚不支持它的环境中使用它:

https://github.com/polymer/WeakMap