當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
哈希表(hashtable)的javascript简单实现
生活随笔
收集整理的這篇文章主要介紹了
哈希表(hashtable)的javascript简单实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
javascript中沒有像c#,java那樣的哈希表(hashtable)的實現。在js中,object屬性的實現就是hash表,因此只要在object上封裝點方法,簡單的使用obejct管理屬性的方法就可以實現簡單高效的hashtable。
首先簡單的介紹關于屬性的一些方法:
屬性的枚舉:
for/in循環是遍歷對象屬性的方法。如
?
var obj = {name : 'obj1',age : 20,height : '176cm' }var str = ''; for(var name in obj) {str += name + ':' + obj[name] + '\n'; } alert(str);?
?
輸出為:name:obj1
age:20
height:176cm
?
檢查屬性是否存在:
in運算符可以用來測試一個屬性是否存在。
this.containsKey = function ( key ) {return (key in entry); }?
?
?
刪除屬性
使用delete運算符來刪除一個對象的屬性。使用delete刪除的屬性,for/in將不會枚舉該屬性,并且in運算符也不會檢測到該屬性。
delete entry[key];delete obj.name;
?
下面是哈希表(hashtable)的js的實現方法:
function HashTable() {var size = 0;var entry = new Object();this.add = function (key , value){if(!this.containsKey(key)){size ++ ;}entry[key] = value;}this.getValue = function (key){return this.containsKey(key) ? entry[key] : null;}this.remove = function ( key ){if( this.containsKey(key) && ( delete entry[key] ) ){size --;}}this.containsKey = function ( key ){return (key in entry);}this.containsValue = function ( value ){for(var prop in entry){if(entry[prop] == value){return true;}}return false;}this.getValues = function (){var values = new Array();for(var prop in entry){values.push(entry[prop]);}return values;}this.getKeys = function (){var keys = new Array();for(var prop in entry){keys.push(prop);}return keys;}this.getSize = function (){return size;}this.clear = function (){size = 0;entry = new Object();} }?
?
?
測試:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/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>
from:http://www.cnblogs.com/hyl8218/archive/2010/01/18/1650589.html
?
?
轉載于:https://www.cnblogs.com/SFAN/p/3669886.html
總結
以上是生活随笔為你收集整理的哈希表(hashtable)的javascript简单实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML5 Canvas 画纸飞机组件
- 下一篇: 微信小程序-使用ColorUI