[size=medium]如题,求教:模拟一个HashTable类,包含add、remove、contains、length方法?[/size]
[quote]
[code="js"]
function Hashtable()
{
this.container = new Object();
/**//** put element */
this.put = function (key, value)
{
if (typeof (key) == "undefined")
{
return false;
}
if (this.contains(key))
{
return false;
}
this.container[key] = typeof (value) == "undefined" ? null : value;
return true;
};
/**//** remove element */
this.remove = function (key)
{
delete this.container[key];
};
/**//** get size */
this.size = function ()
{
var size = 0;
for (var attr in this.container)
{
size++;
}
return size;
};
/**//** get value by key */
this.get = function (key)
{
return this.container[key];
};
/**//** containts a key */
this.contains = function (key)
{
return typeof (this.container[key]) != "undefined";
};
/**//** clear all entrys */
this.clear = function ()
{
for (var attr in this.container)
{
delete this.container[attr];
}
};
/**//** hashTable 2 string */
this.toString = function()
{
var str = "";
for (var attr in this.container)
{
str += "," + attr + "=" + this.container[attr];
}
if(str.length>0)
{
str = str.substr(1, str.length);
}
return "{" + str + "}";
};
}
[/code]
[/quote]
[code="js"]
/* 自定义JavaScript Map实现 */
function Map() {
var struct = function(key, value) {
this.key = key;
this.value = value;
};
var put = function(key, value){
for (var i = 0; i < this.arr.length; i++) {
if ( this.arr[i].key === key ) {
this.arr[i].value = value;
return;
}
}
this.arr[this.arr.length] = new struct(key, value);
};
var get = function(key) {
for (var i = 0; i < this.arr.length; i++) {
if ( this.arr[i].key === key ) {
return this.arr[i].value;
}
}
return null;
};
var remove = function(key) {
var v;
for (var i = 0; i < this.arr.length; i++) {
v = this.arr.pop();
if ( v.key === key ) {
continue;
}
this.arr.unshift(v);
}
};
var size = function() {
return this.arr.length;
};
var isEmpty = function() {
return this.arr.length <= 0;
};
this.arr = new Array();
this.get = get;
this.put = put;
this.remove = remove;
this.size = size;
this.isEmpty = isEmpty;
}
[/code]