js写的一个简单的hashtable,主要用来客户端添加url参数,如param1=value1¶m2=value2¶m3=value3。
有一些js框架也有类似的方法,如有名的prototype框架,而且其还提供所有表单元素,直接serialize成url参数形式。很久前用过
一段时间,不过现在一般用jQuery。废话少说,贡献出来,和大家交流与批评指正。
/*
* create by hjp
* blog:http://jackhuclan.cnblogs.com
* 2009-01-08
* usage for append or remove parameters to url
*/
var HashTable = function sg_HashTable()
{
this.__hash=new ActiveXObject("Scripting.Dictionary");
this.Items=[];
this.__Keys=null;
this.__Values=null;
}
HashTable.prototype={
add:function(key,value)
{
if(this.__hash.Exists(key))
{
this.__hash.Remove(key);
var pos=this.find(key);
if(pos!=-1)
{
this.Items[pos].Value=value;
}
this.__hash.Add(key,value);
}
else
{
this.__hash.Add(key,value);
this.Items.push({"Key":key,"Value":value});
}
},
remove:function(key)
{
if(this.__hash.Exists(key))
{
this.__hash.Remove(key);
var pos=this.find(key);
if(pos!=-1)
{
var newArr= this.Items.slice(0, pos).concat(this.Items.slice(pos + 1, this.Items.length));
delete this.Items;
this.Items=newArr;
}
}
},
removeAll:function()
{
this.__hash.RemoveAll();
delete this.Items;
this.Items=[];
},
getKeys:function(){
this.__Keys=[];
for(var i=0;i<this.Items.length;i++)
{
var item=this.Items[i];
this.__Keys.push(item.Key);
}
return this.__Keys;
},
getValues:function(){
this.__Values=[];
for(var i=0;i<this.Items.length;i++)
{
var item=this.Items[i];
this.__Values.push(item.Value);
}
return this.__Values;
},
toUrl:function()
{
var str="";
for(var i=0;i<this.Items.length-1;i++)
{
var item=this.Items[i];
if(encodeURIComponent)
str += encodeURIComponent(item.Key)+"="+encodeURIComponent(item.Value)+"&";
else
str += escape(item.Key)+"="+escape(item.Value)+"&";
}
var lastItem=this.Items[this.Items.length-1];
if(encodeURIComponent)
str += encodeURIComponent(lastItem.Key)+"="+encodeURIComponent(lastItem.Value);
else
str += escape(lastItem.Key)+"="+escape(lastItem.Value);
return str;
},
find:function(key)
{
for(var i=0;i<this.Items.length;i++)
{
var item=this.Items[i];
if(item.Key==key)
{
return i;
}
}
return -1;
}
}
客户端调用如下:
<script type="text/javascript">
var hs=new HashTable();
hs.add("id1","1");
hs.add("id2","张三");
hs.add("id2","dddd");
hs.add("id4","4");
var str=hs.toUrl();
debugger
hs.getKeys();
hs.getValues();
hs.remove("id4");
debugger
hs.removeAll();
</script>