用Javascript写的一个映射表类

王朝html/css/js·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航