However, please make a careful comparison and you will find that the difference is still very big. The key of Java HashMap is of the Object type, so it can be any type of parameter, and the key of JS can only be a string or number. You may say that obj = {}; map [obj] = 1; this code has passed in a key that is neither a number nor a character, but there is no error. That's because the interpreter converts the obj object to the "[Object object]" character using the built-in toString method. You can use map under for each to see it. Java accepts keys of any type because its Object implements the HashCode method, and each class inherits or overwrites the HashCode of the Object. Therefore, any variable has a hash value. We can also try it with JS.
As mentioned above, the toString method is used to convert any type into characters. Similarly, it has another method: valueOf, which is used to convert data into numbers. Because numbers are easier to index, we first try valueOf:
Copy codeThe Code is as follows:
Object. prototype. valueOf = function ()
{
Alert ("Hello ~ ")
};
Var map = [];
Var obj = {};
Map [obj] = 1;
The result was disappointing. The dialog box did not jump out, indicating that the JS engine did not try to convert the obj object into a number. Next, try to change it to the toString method:
Copy codeThe Code is as follows:
Object. prototype. toString = function ()
{
Alert ("Hello ~ ")
};
Var map = {};
Var obj = {};
Map [obj] = 1;
The dialog box jumps out. Of course, no data is returned, and this 1 is saved in map ["undefined. However, if we return a value and ensure that each variable has a unique value, we can use the original map [key] method to index any type. We reload the toString method of the Object:
Copy codeThe Code is as follows:
Var HASH_ID = 0;
Object. prototype. toString = function ()
{
If (this. _ HASH = null)
This. _ HASH = HASH_ID ++;
Return "Obj:" + this. _ HASH;
};
Let's test it below:
Copy codeThe Code is as follows:
Var HashMap = {};
Var obj1 = {};
Var obj2 = {};
HashMap [obj1] = "Foo1 ";
HashMap [obj2] = "Foo2 ";
Alert (HashMap [obj1] + "&" + HashMap [obj2]);
HashMap [obj1] = "Bar1 ";
HashMap [obj2] = "Bar2 ";
Alert (HashMap [obj1] + "&" + HashMap [obj2]);
Output: Foo1 & Foo2 and Bar1 & Bar2 respectively, which indicates that obj1 and obj2 always correspond to the same index.
Of course, if the object itself overwrites the toString method, it may not necessarily have different values returned each time. Therefore, you must make corresponding adjustments based on the actual situation. )