First, a brief introduction to some methods about attributes:
Enumeration of attributes:
The for/in loop is a method of traversing the attributes of an object. For example,
var obj = {
name : 'obj1 ',
age : 20,
height : '176cm'
}
var str = '';
for(var name in obj)
{
str = name ':' obj[name] 'n';
}
alert(str);
The output is: name:obj1
Age:20
Height: 176cm
Check if an attribute exists: The
in operator can be used to test whether an attribute exists.
this.containsKey = function ( key )
{
return (key in entry);
}
Delete attributes
Use the delete operator to delete attributes of an object. With delete, the property will not be enumerated by for/in and will not be detected by the in operator.
delete entry[key];
delete obj.name;
The following is the js implementation method of hashtable:
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