当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 用Javascript写的一个映射表类

Javascript
用Javascript 实现的Dual listbox
javascript中的数组应用的一点发现
我与Javascript 随笔(二)
关于IP验证的一个例子
JS中关于对内存的释放问题[待续]
用JScript实现公历到农历的日期转换
判断输入字符串为颜色类型的最优方法
日期控件还是看看这个吧
javascript版的日期输入控件
可输入的select改进版本,同一页面可有多个list,调用接口简化
数字金额转换汉字金额
关于四舍五入的问题,toFixed()
Select的OnChange()事件
关于javascript树形结构的编写问题
将人民币数字转换成大写形式
用JavaScript实现动画效果
javascript: 改变和控制显示的图片大小(保持比例,同时可限制高宽)
超强幻灯片播放脚本(VBS)
HTML页面如何象asp一样接受参数
数字日期转化为汉字日期格式...

用Javascript写的一个映射表类


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-10   浏览: 153 ::
收藏到网摘: n/a

该类可以通过关键字(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>