战剑网络,网站建设,系统开发,程序设计

搜索Top
用Javascript写的一个映射表类


搜索关键字:

该类可以通过关键字(key)查找相对应的值(value),关键字的类型可以是string、number、boolean类型,值的类型不限,代码如下:

<script>
function struct(key, value){

  this.key = key;
  this.value = value;

}

function setat(key, value){
 


  for (var i = 0; i < this.map.length; i++)
  {
    if ( this.map[i].key === key )
    {
      this.map[i].value = value;
      return;
    }
  }
 
  this.map[this.map.length] = new struct(key, value);

}

function lookup(key)
{
  for (var i = 0; i < this.map.length; i++)
  {
    if ( this.map[i].key === key )
    {
      return this.map[i].value;
    }
  }
 
  return null;
}

function removekey(key)
{
  var v;
  for (var i = 0; i < this.map.length; i++)
  {
    v = this.map.pop();
    if ( v.key === key )
      continue;
     
    this.map.unshift(v);
  }
}

function getcount(){
  return this.map.length;
}

function isempty(){
  return this.map.length <= 0;
}

function classmap() {

  this.map = new array();

  this.lookup = lookup;
  this.setat = setat;
  this.removekey = removekey;
  this.getcount = getcount;
  this.isempty = isempty;
}

window.onload = function(){

  var map = new classmap();

  alert("is the map empty? " + map.isempty());
 
  // string to array
  map.setat("sw1", new array("sw1_1"));
  map.setat("sw2", new array("sw2_1", "sw2_2"));
  map.setat("sw3", new array("sw3_1", "sw3_2", "sw3_3"));
  alert(map.lookup("sw5")); // null
  alert(map.lookup("sw2")); // "sw2_1, sw2_2"
 
  alert(map.getcount()); // 3
 
  // number to string
  map.setat(1, "sw1");
  map.setat(2, "sw2");
  alert(map.lookup(2)); // "sw2"
  map.setat(2, new array("sw2_1", "sw2_2"));
  alert(map.lookup(2)); // "sw2_1, sw2_2"
 
  alert(map.getcount()); // 5
 
  // string to number
  map.setat("1", 1);
  map.setat("2", 2);
  alert(map.lookup("1")); // 1
  alert(map.lookup(1)); // "sw1"
  map.setat("sw3", 33);
  alert(map.lookup("sw3")); // 33
 
  alert(map.getcount()); // 7


 
  // number to number
  map.setat(1, 11);
  map.setat(2, 22);
  alert(map.lookup(1)); // 11
 
  alert(map.getcount()); // 7
 
  map.removekey(1);
  alert(map.lookup(1)); // null
 
  alert(map.getcount()); // 6
 
  // boolean to array
  map.setat(false, new array("false", "true"));
  alert(map.lookup(false));
 
  alert(map.getcount()); // 7

}
</script>


[ 打印本页 ] [ 收藏本页 ]

[上一篇]:已经到顶了
[下一篇]:JavaScript应用:Iframe自适应其加载的内容高度
 ·SEO:Yahoo和Google在搜索上的区别
 ·网页制作高手进阶:网页设计中的文字运用
 ·商业网站设计主要原则
 ·跟我看搜索引擎服务优势
 ·我常用的一些网站测评方法

特别声明:本站除部分特别声明禁止转载的专稿外的其他文章可以自由转载,但请务必注明出处和原始作者。文章版权归文章原始作者所有。对于被本站转载文章的个人和网站,我们表示深深的谢意。如果本站转载的文章有版权问题请联系编辑人员,我们尽快予以更正。
搜索Top

关于我们 - 联系我们 - 广告业务 - 友情链接 - 网站制作 - 留言板 - 会员注册
All Right Zjm.Net.Cn (zjm Enterprise v3.0)
联系电话:0576-8603312 地址:浙江省台州市经济开发区
技术支持:点击这里给我发消息280610248 业务: 点击这里给我发消息40520767 客服: 点击这里给我发消息441758646
E-mail:zjm@zjm.net.cn 备案证书号:浙ICP备06030047号