复制代码代码如下:
function Hashtable() //自定义hashtable
{
this._hash = new Object();
this.add = function(chave, valor) {
if (typeof (chave)! = "indefinido") {
if (this.contains(chave) == falso) {
this._hash[key] = typeof (valor) == "indefinido"? nulo: valor;
retornar verdadeiro;
} outro {
retornar falso;
}
} outro {
retornar falso;
}
}
this.remove = function(key) { excluir this._hash[key]; }
this.count = function() { var i = 0; for (var k neste._hash) { i++; } retornar eu; }
this.items = function(key) { return this._hash[key]; }
this.contains = function(key) { return typeof (this._hash[key]) != "indefinido"; }
this.clear = function() { for (var k in this._hash) { excluir this._hash[k]; } }
}
复制代码代码如下:
//js哈希表
função HashTable() {
this.ObjArr = {};
isto.Contagem = 0;
//添加
this.Add = function(chave, valor) {
if (this.ObjArr.hasOwnProperty(chave)) {
retornar falso; //如果键已经存在,不添加
}
outro {
this.ObjArr[chave] = valor;
isto.Contagem++;
retornar verdadeiro;
}
}
//是否包含某项
this.Contains = function(chave) {
retorne this.ObjArr.hasOwnProperty(chave);
}
//取某一项 其实等价于this.ObjArr[chave]
this.GetValue = function(chave) {
if (this.Contém(chave)) {
retorne isto.ObjArr[chave];
}
outro {
throw Error("Hashtable não contém a chave: " + String(key)); //脚本错误
//retornar;
}
}
//移除
this.Remove = function(chave) {
if (this.Contém(chave)) {
exclua isto.ObjArr[chave];
this.Contagem--;
}
}
//清空
isto.Limpar = function() {
this.ObjArr = {}; isto.Contagem = 0;
}
}
测试代码:
//员工
função funcionário(id, nome_do_usuário) {
isto.id = id;
this.userName = nome do usuário;
}
teste de função() {
var ht = new HashTable();
var tmpEmployee = null;
for (var i = 1; i < 6; i++) {
tmpEmployee = novo funcionário(i, "Employee_" + i);
ht.Add(i, tmpEmployee);
}
for (var i = 1; i <= ht.Count; i++) {
alerta(ht.GetValue(i).userName); //其实等价于ht.ObjArr[i].userName
//alert(ht.ObjArr[i].userName);
}
ht.Remover(1);
alerta(ht.Contém(1)); //falso
alerta(ht.Contém(2)); //verdadeiro
//alert(ht.GetValue(1)); //异常
var resultado = ht.GetValue(2);
if (resultado! = nulo) {
alert("Id do funcionário:" + result.id + ";UserName:" + result.userName);
}
ht.Add(2, "这一个key已经存在!"); //Adicionar无效
//ht.Clear(); //清空
alerta(ht.Contagem);
}