Javascript does not implement a hash table (hashtable) like c # and java. In js, the implementation of object attributes is the hash table. Therefore, as long as the point method is encapsulated on the object, the simple and efficient hashtable can be implemented simply by using obejct to manage attributes. First, we will briefly introduce some methods for attributes:
Attribute enumeration:
For/in loops are used to traverse object attributes. For example
The Code is as follows:
Var obj = {
Name: 'obj1 ',
Age: 20,
Height: '20180101'
}
Var str = '';
For (var name in obj)
{
Str + = name + ':' + obj [name] + '\ n ';
}
Alert (str );
Output: name: obj1
Age: 20
Height: 176
Check whether the property exists:
The in operator can be used to test whether an attribute exists.
The Code is as follows:
This. containsKey = function (key)
{
Return (key in entry );
}
Delete attributes
Use the delete operator to delete the attributes of an object. If you delete an attribute by using delete, for/in does not enumerate the attribute, and the in operator does not detect the attribute.
Delete entry [key];
Delete obj. name;
The following describes how to implement the js of a hash table (hashtable:
The Code is as follows:
Function HashTable ()
{
Var size = 0;
Var entry = new Object ();
This. add = function (key, value)
{
If (! This. containsKey (key ))
{
Size ++;
}
Entry [key] = value;
}
This. getValue = function (key)
{
Return this. containsKey (key )? Entry [key]: null;
}
This. remove = function (key)
{
If (this. containsKey (key) & (delete entry [key])
{
Size --;
}
}
This. containsKey = function (key)
{
Return (key in entry );
}
This. containsValue = function (value)
{
For (var prop in entry)
{
If (entry [prop] = value)
{
Return true;
}
}
Return false;
}
This. getValues = function ()
{
Var values = new Array ();
For (var prop in entry)
{
Values. push (entry [prop]);
}
Return values;
}
This. getKeys = function ()
{
Var keys = new Array ();
For (var prop in entry)
{
Keys. push (prop );
}
Return keys;
}
This. getSize = function ()
{
Return size;
}
This. clear = function ()
{
Size = 0;
Entry = new Object ();
}
}
Test:
Code
The Code is as follows:
HashTable