自己打造一个ASP集合类

      在ASP开发中,往往苦于数据结构的贫乏,通常的做法是通过创建Scripting.Dictionary对象来得到一个集合类,但在有些情况下,Scripting.Dictionary组件被管理员禁用,我们会束手无策。最近我就碰到这样一个问题,我申请的一个免费ASP空间无法创建Scripting.Dictionary,无可奈何!
       后来我想,能不能不依赖于服务器的组件,自己写一个真正无组件集合类呢?不动手怎么知道行不行呢,说干就干。
       首先想到的是用数组来存储数据,但是VBScript中处理不定长数组比较麻烦,而且VBScript中的数组也不能按中字符串的键值来取值,于是决定用JScript来实现,怎么考虑的过程就不多说了,代码胜于一切描述:
<SCRIPT RUNAT=SERVER LANGUAGE=JSCRIPT>
//创建Map对象
function CreateMap() { return new Map(); }
//自定义的Map对象
function Map() {
this.Items = new Array();
this.Add = function(key, value) {
  this.Items[key] = value;
}
this.Remove = function(key) {
  this.Items[key] = null;
    var tmpItems = new Array();
    jj=0;
    for(ii=0; ii<this.Items.length; ii++) {
      if(this.Items[ii]==null) continue;
      tmpItems[jj++] = this.Items[ii];
    }
    this.Items = tmpItems;
  }
  this.Len = function() {
    return this.Items.length;
  }
  this.Get = function(key) {
    return this.Items[key];
  }
}
</SCRIPT>

调用时跟调用Scripting.Dictionary没有太大差别,例子如下:
<html>
<head>
<SCRIPT RUNAT="SERVER" LANGUAGE="JSCRIPT">
function CreateMap() { return new Map(); }
//自定义的Map对象
function Map() {
this.Items = new Array();
this.Add = function(key, value) {
  this.Items[key] = value;
}
this.Remove = function(key) {
  this.Items[key] = null;
    var tmpItems = new Array();
    jj=0;
    for(ii=0; ii<this.Items.length; ii++) {
      if(this.Items[ii]==null) continue;
      tmpItems[jj++] = this.Items[ii];
    }
    this.Items = tmpItems;
  }
  this.Len = function() {
    return this.Items.length;
  }
  this.Get = function(key) {
    return this.Items[key];
  }
}
</SCRIPT>
</head>

<body>
<%
Set Fields = CreateMap()
for ii=1 to 10
  Fields.Add CStr(ii), "这是Item:" + CStr(ii)
Next ii
For Each Field In Fields.Items
  Response.write Field + "<br>"
next
%>
</body>
</html>



你可能感兴趣的:(数据结构,VBScript,asp)