复制代码代码如下 :
function Hashtable()//自定义hashtable
{
this._hash = new Object();
this.add = fonction (clé, valeur) {
if (typeof (key) != "indéfini") {
if (this.contains(key) == false) {
this._hash[key] = typeof (value) == "indéfini" ? nul : valeur ;
renvoie vrai ;
} autre {
renvoie faux ;
}
} autre {
renvoie faux ;
}
}
this.remove = function(key) { delete this._hash[key]; }
this.count = function() { var je = 0; for (var k dans this._hash) { i++; } retourne je; }
this.items = function(key) { return this._hash[key]; }
this.contains = function(key) { return typeof (this._hash[key]) != "indéfini"; }
this.clear = function() { for (var k in this._hash) { delete this._hash[k]; } }
}
复制代码代码如下 :
// js哈希表
fonction HashTable() {
this.ObjArr = {};
this.Count = 0 ;
//添加
this.Add = fonction (clé, valeur) {
if (this.ObjArr.hasOwnProperty(key)) {
renvoie faux ; //如果键已经存在,不添加
}
autre {
this.ObjArr[clé] = valeur ;
ceci.Count++;
renvoie vrai ;
}
}
//是否包含某项
this.Contient = fonction (clé) {
renvoie this.ObjArr.hasOwnProperty(key);
}
//取某一项 其实等价于this.ObjArr[key]
this.GetValue = fonction (clé) {
if (this.Contains(key)) {
renvoie this.ObjArr[clé];
}
autre {
throw Error("La table de hachage ne contient pas la clé : " + String(key)); //脚本错误
//retour;
}
}
//移除
this.Remove = fonction (clé) {
if (this.Contains(key)) {
supprimez this.ObjArr[key];
this.Count--;
}
}
//清空
this.Clear = fonction() {
this.ObjArr = {}; this.Count = 0 ;
}
}
测试代码 :
//员工
fonction employé (id, nom d'utilisateur) {
this.id = identifiant;
this.userName = nom d'utilisateur ;
}
fonction test() {
var ht = nouveau HashTable();
var tmpEmployee = null;
pour (var je = 1; je < 6; je++) {
tmpEmployee = nouvel employé (i, "Employee_" + i);
ht.Add(i, tmpEmployee);
}
pour (var i = 1; i <= ht.Count; i++) {
alert(ht.GetValue(i).userName); //其实等价于ht.ObjArr[i].userName
//alerte(ht.ObjArr[i].userName);
}
ht.Remove(1);
alerte(ht.Contains(1)); //FAUX
alerte(ht.Contains(2)); //vrai
//alerte(ht.GetValue(1)); //异常
var résultat = ht.GetValue(2);
si (résultat != null) {
alert("Id de l'employé :" + result.id + ";UserName:" + result.userName);
}
ht.Add(2, "这一个key已经存在!"); //Ajouter无效
//ht.Clear(); //清空
alerte(ht.Count);
}