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

