轉(zhuǎn)自http://www.cnblogs.com/hyl8218/archive/2010/01/18/1650589.html
javascript中沒有像c#,java那樣的哈希表(hashtable)的實現(xiàn),。在js中,object屬性的實現(xiàn)就是hash表,因此只要在object上封裝點方法,簡單的使用obejct管理屬性的方法就可以實現(xiàn)簡單高效的hashtable,。 首先簡單的介紹關(guān)于屬性的一些方法: 屬性的枚舉: for/in循環(huán)是遍歷對象屬性的方法。如
1 var obj = {
2 name : 'obj1', 3 age : 20, 4 height : '176cm' 5 } 6 7 var str = ''; 8 for(var name in obj) 9 { 10 str += name + ':' + obj[name] + '\n'; 11 } 12 alert(str);
輸出為:name:obj1 age:20 height:176cm
檢查屬性是否存在: in運算符可以用來測試一個屬性是否存在,。 this.containsKey = function ( key )
{ return (key in entry); }
刪除屬性 使用delete運算符來刪除一個對象的屬性。使用delete刪除的屬性,for/in將不會枚舉該屬性,并且in運算符也不會檢測到該屬性。 1 delete entry[key];
2 delete obj.name;
1 function HashTable()
2 { 3 var size = 0; 4 var entry = new Object(); 5 6 this.add = function (key , value) 7 { 8 if(!this.containsKey(key)) 9 { 10 size ++ ; 11 } 12 entry[key] = value; 13 } 14 15 this.getValue = function (key) 16 { 17 return this.containsKey(key) ? entry[key] : null; 18 } 19 20 this.remove = function ( key ) 21 { 22 if( this.containsKey(key) && ( delete entry[key] ) ) 23 { 24 size --; 25 } 26 } 27 28 this.containsKey = function ( key ) 29 { 30 return (key in entry); 31 } 32 33 this.containsValue = function ( value ) 34 { 35 for(var prop in entry) 36 { 37 if(entry[prop] == value) 38 { 39 return true; 40 } 41 } 42 return false; 43 } 44 45 this.getValues = function () 46 { 47 var values = new Array(); 48 for(var prop in entry) 49 { 50 values.push(entry[prop]); 51 } 52 return values; 53 } 54 55 this.getKeys = function () 56 { 57 var keys = new Array(); 58 for(var prop in entry) 59 { 60 keys.push(prop); 61 } 62 return keys; 63 } 64 65 this.getSize = function () 66 { 67 return size; 68 } 69 70 this.clear = function () 71 { 72 size = 0; 73 entry = new Object(); 74 } 75 }
測試: 代碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml"> <head> <title>HashTable</title> <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/javascript" src="/js/HashTable.js"></script> <script type="text/javascript"> function MyObject(name) { this.name = name; this.toString = function(){ return this.name; } } $(function(){ var map = new HashTable(); map.add("A","1"); map.add("B","2"); map.add("A","5"); map.add("C","3"); map.add("A","4"); var arrayKey = new Array("1","2","3","4"); var arrayValue = new Array("A","B","C","D"); map.add(arrayKey,arrayValue); var value = map.getValue(arrayKey); var object1 = new MyObject("小4"); var object2 = new MyObject("小5"); map.add(object1,"小4"); map.add(object2,"小5"); $('#console').html(map.getKeys().join('|') + '<br>'); }) </script> </head> <body> <div id="console"></div> </body> </html> |
|