js 類比實作類別似c#下的hashtable的簡易功能代碼

來源:互聯網
上載者:User

如果在c#中,我們只要用hashtable或者dictionary根據key取value的特性,就可以很輕鬆地實現這個功能了。其實我們稍作處理,js也可以實作類別似hashtable的功能。下面總結一下筆者開發中用到的實現方式,貼代碼為主。
1、實現思路:主要就是利用原型(prototype)的hasOwnProperty方法,確定對象中的項是該添加、移除還是取出某個匹配的項等。hasOwnProperty比遍曆數組取值靈巧快速的地方在於:至少從代碼上來看,它是O(1)複雜度的。
2、實現代碼 複製代碼 代碼如下:// 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;
}
}

3、測試代碼
代碼 複製代碼 代碼如下://員工
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);
}

調用的時候很簡單,只要new一個hashtable對象,常見的功能就都有了。是不是很簡單?Enjoy it。
小結:原型鏈(prototype鏈)和範圍鏈是js的兩個最核心的部分。學懂並悟透它們,許多複雜問題都會迎刃而解;好好利用它們的特性,我們可以輕鬆實現非常靈活高效的功能。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.