Javascript is increasingly not as powerful as C # in processing collections. For example, in actual development, it is often used to retrieve an item that meets certain conditions in a one-dimensional array or two-dimensional array. The common processing method is to traverse the array, compare the conditions, and retrieve the matching, then end the loop. In C #, we can easily implement this function by using hashtable or dictionary to obtain value based on the key feature. As a matter of fact, JS can also implement features similar to hashtable. The following summarizes the implementation methods used in the development by the author.CodeMainly.
1. Implementation idea: The main idea is to use the hasownproperty method of prototype to determine whether an item in the object is to be added, removed, or retrieved. Hasownproperty is less efficient than traversing arrays because it is O (1) complex, at least in code.
2. Implementation Code
Code
// JS hash table
Function hashtable (){
This. Objarr={};
This. Count= 0;
// Add
This . Add = Function (Key, value ){
If ( This . Objarr. hasownproperty (key )){
Return False ; // If the key already exists, do not add
}
Else {
This . Objarr [Key] = Value;
This . Count ++ ;
Return True ;
}
}
//Include a certain item
This. Contains=Function (key ){
Return This. Objarr. hasownproperty (key );
}
// Retrieving a certain item is equivalent to this. objarr [Key].
This . Getvalue = Function (key ){
If ( This . Contains (key )){
Return This . Objarr [Key];
}
Else {
Throw Error ( " Hashtable not cotains the key: " + String (key )); // Script Error
// Return;
}
}
// Remove
This . Remove = Function (key ){
If ( This . Contains (key )){
Delete This . Objarr [Key];
This . Count -- ;
}
}
//Clear
This. Clear=Function (){
This. Objarr={};This. Count= 0;
}
}
3. Test code
Code
// Employee
Function Employee (ID, username ){
This . ID = ID;
This . Username = Username;
}
FunctionTest (){
VaR HT = New Hashtable ();
VaR Tmpemployee = Null ;
For ( VaR I = 1 ; I < 6 ; I ++ ){
Tmpemployee = New Employee (I, " Employee _ " + I );
Ht. Add (I, tmpemployee );
}
For ( VaR I = 1 ; I <= Ht. Count; I ++ ){
Alert (HT. getvalue (I). username ); // It is equivalent to HT. objarr [I]. username.
// Alert (HT. objarr [I]. username );
}
Ht. Remove ( 1 );
Alert (HT. Contains ( 1 )); // False
Alert (HT. Contains ( 2 )); // True
// Alert (HT. getvalue (1); // exception
VaR Result = Ht. getvalue ( 2 );
If (Result ! = Null ){
Alert ( " Employee ID: " + Result. ID + " ; Username: " + Result. username );
}
Ht. Add ( 2 , " This key already exists! " ); // Invalid add
// Ht. Clear (); // clear
Alert (HT. Count );
}
Calling is simple. as long as a new hashtable object is called, common functions are available. Is it easy? Enjoy it.
Summary: prototype chain and scope chain are the two core parts of Js. Learn and understand them, and solve many complex problems. By taking advantage of their features, we can easily implement very flexible and efficient functions.