js模拟hashtable的简单实例_javascript技巧
function Hashtable()//自定义hashtable
{
this._hash = new Object();
this.add = function(key, value) {
if (typeof (key) != "undefined") {
if (this.contains(key) == false) {
this._hash[key] = typeof (value) == "undefined" ? null : value;
return true;
} else {
return false;
}
} else {
return false;
}
}
this.remove = function(key) { delete this._hash[key]; }
this.count = function() { var i = 0; for (var k in this._hash) { i++; } return i; }
this.items = function(key) { return this._hash[key]; }
this.contains = function(key) { return typeof (this._hash[key]) != "undefined"; }
this.clear = function() { for (var k in this._hash) { delete this._hash[k]; } }
}
// js哈希表
function HashTable() {
this.ObjArr = {};
this.Count = 0;
//添加
this.Add = function(key, value) {
if (this.ObjArr.hasOwnProperty(key)) {
return false; //如果键已经存在,不添加
}
else {
this.ObjArr[key] = value;
this.Count++;
return true;
}
}
//是否包含某项
this.Contains = function(key) {
return this.ObjArr.hasOwnProperty(key);
}
//取某一项 其实等价于this.ObjArr[key]
this.GetValue = function(key) {
if (this.Contains(key)) {
return this.ObjArr[key];
}
else {
throw Error("Hashtable not cotains the key: " + String(key)); //脚本错误
//return;
}
}
//移除
this.Remove = function(key) {
if (this.Contains(key)) {
delete this.ObjArr[key];
this.Count--;
}
}
//清空
this.Clear = function() {
this.ObjArr = {}; this.Count = 0;
}
}
测试代码:
//员工
function employee(id, userName) {
this.id = id;
this.userName = userName;
}
function test() {
var ht = new HashTable();
var tmpEmployee = null;
for (var i = 1; i tmpEmployee = new employee(i, "Employee_" + i);
ht.Add(i, tmpEmployee);
}
for (var i = 1; i alert(ht.GetValue(i).userName); //其实等价于ht.ObjArr[i].userName
//alert(ht.ObjArr[i].userName);
}
ht.Remove(1);
alert(ht.Contains(1)); //false
alert(ht.Contains(2)); //true
//alert(ht.GetValue(1)); //异常
var result = ht.GetValue(2);
if (result != null) {
alert("Employee Id:" + result.id + ";UserName:" + result.userName);
}
ht.Add(2, "这一个key已经存在!"); //Add无效
//ht.Clear(); //清空
alert(ht.Count);
}
上一篇: php date()日期时间函数详解
推荐阅读
-
js类的静态属性和实例属性的理解_javascript技巧
-
JS实现简单的顶部定时关闭层效果_javascript技巧
-
js 文本滚动效果的实例代码_javascript技巧
-
JS将表单导出成EXCEL的实例代码_javascript技巧
-
js实现DIV的一些简单控制_javascript技巧
-
js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)_javascript技巧
-
用原生js做个简单的滑动效果的回到顶部_javascript技巧
-
一个简单的js树形菜单_javascript技巧
-
js控制不同的时间段显示不同的css样式的实例代码_javascript技巧
-
js改变文章字体大小的实例代码_javascript技巧