javascript中,object的實現就是hash表,因此只要在object上封裝點方法,再利用原生的hasOwnProperty方法就可以實現簡單高效的hashtable
var HashTable = Class.create();
HashTable.prototype=
{
initialize:function()
{
this._content ={};
},
Count:function()
{
var count = 0;
for(var i in this._content) count++;
return count;
},
Items:function(key)
{
if(this.Contains(key))
{
return this._content[key];
}
},
Add:function(key,value)
{
if(this._content.hasOwnProperty(key))
{
return false;
}
else
{
this._content[key] = value;
return true;
}
},
Clear:function()
{
this._content = {};
},
Contains:function(key)
{
return this._content.hasOwnProperty(key);
},
Remove:function(key)
{
delete this._content[key];
}
}
測試如下:Code
<!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>Untitled Page</title>
<script src="../O.cn_My/js/prototype.js" type="text/javascript"></script>
<script src="hashtable.js" type="text/javascript"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
var hashtable = new HashTable();
for(var i = 0 ;i<100000;i++)
{
hashtable.Add(i*1.2,i);
}
var now = (new Date()).getTime();
var temp ="";
for(var i=0;i<1000;i++)
{
if(hashtable.Contains(1+i*2.8))
{
hashtable.Remove(i*2.8);
}
}
hashtable.Clear();
$("output").innerHTML = " time pass:"+((new Date()).getTime()-now)+"ms";
//alert(hashtable.Count());
</script>
</html>
得出的結果是,100000大的hash表,進行1000次的判斷,才花費15ms. 很快的速度了,可以用來做程式的最佳化.
注意: 字串和數字相加會有糟糕的效率,導致時間多花了一倍,影響測試.