A ing table class written in Javascript
This class can use the key to find the corresponding value. The key type can be string, number, or Boolean. The value type is not limited. The Code is as follows:
<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>