复制代码代码如下:
función Hashtable()//自定义hashtable
{
this._hash = nuevo Objeto();
this.add = función (clave, valor) {
if (tipo de (clave)! = "indefinido") {
si (esto.contiene(clave) == falso) {
this._hash[clave] = tipo de (valor) == "indefinido"? nulo: valor;
devolver verdadero;
} demás {
devolver falso;
}
} demás {
devolver falso;
}
}
this.remove = function(key) { eliminar this._hash[key]; }
this.count = función() { var i = 0; for (var k en this._hash) { i++; } devolver yo; }
this.items = function(clave) { return this._hash[clave]; }
this.contains = function(key) { return typeof (this._hash[key]) != "indefinido"; }
this.clear = function() { para (var k en this._hash) { eliminar this._hash[k]; } }
}
复制代码代码如下:
// js哈希表
función HashTable() {
this.ObjArr = {};
esto.Cuenta = 0;
//添加
this.Add = función (clave, valor) {
si (this.ObjArr.hasOwnProperty(clave)) {
devolver falso; //如果键已经存在,不添加
}
demás {
this.ObjArr[clave] = valor;
this.Count++;
devolver verdadero;
}
}
//是否包含某项
this.Contains = función (clave) {
devolver this.ObjArr.hasOwnProperty(clave);
}
//取某一项 其实等价于this.ObjArr[clave]
this.GetValue = función (clave) {
si (esto.Contiene(clave)) {
devuelve this.ObjArr[clave];
}
demás {
throw Error("Hashtable no contiene la clave: " + String(clave)); //脚本错误
//devolver;
}
}
//移除
this.Remove = función (tecla) {
si (esto.Contiene(clave)) {
eliminar this.ObjArr[key];
this.Count--;
}
}
//清空
this.Clear = función() {
this.ObjArr = {}; esto.Cuenta = 0;
}
}
测试代码:
//员工
función empleado (id, nombre de usuario) {
this.id = identificación;
this.userName = nombre de usuario;
}
prueba de función() {
var ht = nueva HashTable();
var tmpEmpleado = nulo;
para (var i = 1; i < 6; i++) {
tmpEmpleado = nuevo empleado(i, "Empleado_" + i);
ht.Add(i, tmpEmpleado);
}
for (var i = 1; i <= ht.Count; i++) {
alerta(ht.GetValue(i).nombredeusuario); //其实等价于ht.ObjArr[i].userName
//alert(ht.ObjArr[i].nombredeusuario);
}
ht.Remove(1);
alerta(ht.Contiene(1)); //FALSO
alerta(ht.Contiene(2)); //verdadero
//alerta(ht.GetValue(1)); //异常
resultado var = ht.GetValue(2);
si (resultado! = nulo) {
alert("Id. de empleado:" + resultado.id + ";Nombre de usuario:" + resultado.nombre de usuario);
}
ht.Add(2, "这一个key已经存在!"); //Añadir无效
//ht.Clear(); //清空
alerta(ht.Count);
}