复制代码 代码如下:
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 < 6; i++) {
tmpEmployee = new employee(i, "Employee_" + i);
ht.Add(i, tmpEmployee);
}
for (var i = 1; i <= ht.Count; 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);
}
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 罗大佑-无法盗版的青春套装版10CD【WAV】
- 张学友《意乱情迷》蜚声环球 2024 [WAV+CUE][1G]
- 柏菲《好歌30年特别版2CD》最好听的影视歌曲[低速原抓WAV+CUE][1G]
- 张学友《世纪10星·永恒篇》香港版[WAV+CUE][1G]
- 模拟之声慢刻CD《刘德海.琵琶独奏精逊【低速原抓WAV+CUE】
- Jamettone-18052023—improv(EDit)(2024)【FLAC】
- 【索尼精芽20首最棒的苏格兰歌曲集【FLAC】
- 池约翰C.J《少年白马醉春风2 动画原声带》[320K/MP3][26.67MB]
- 池约翰C.J《少年白马醉春风2 动画原声带》[FLAC/分轨][144.13MB]
- 陈致逸《幻想乐园 Fantasyland》[320K/MP3][120.54MB]
- 席卷全球最红舞曲《火辣辣DJ[英文版]》[DTS-WAV]
- 群星-席卷全球最红舞曲《火辣辣DJ中文版》【WAV】
- 模拟之声慢刻CD《声入人心[年度发烧人声严选]》[低速原抓WAV+CUE]
- 陈致逸《幻想乐园 Fantasyland》[FLAC/分轨][554.27MB]
- Rhymist / LusciousBB《年轮》[320K/MP3][76.52MB]