JavaScript often encounters some key-value pairs, which were previously implemented using two-dimensional arrays. Today, we simply simulate the Dictionary help class.
Principle: Create an object that contains two Arrays: Key Array and value Array. Call the JavaScript Array object method.
W3C reference: http://www.w3school.com.cn/js/jsref_obj_array.asp
The BuildDictionary () method is used to create a Dictionary object containing two arrays.
The AddItem method calls the push method of the JavaScript Array object to append the key and value to the corresponding Array.
The UpdateItem method is used to change the corresponding value.
The DeleteItem method calls the Splice method of the JavaScript Array object to delete elements. The first parameter is the index of the elements to be deleted, and the first parameter represents the number of deleted elements.
GetKeyStr is used to obtain the string after splicing the Keys array.
GetValueStr is used to obtain the string after the Values array is spliced.
There are five methods:
/* Create a Dictionary */
Function BuildDictionary (){
Dic = new Object ();
Dic. Keys = new Array (); // key Array
Dic. Values = new Array (); // value Array
Return dic;
}
/* Add key, value */
Function AddItem (key, value, dic ){
Var keyCount = dic. Keys. length;
If (keyCount> 0 ){
Var flag = true;
For (var I = 0; I <keyCount; I ++ ){
If (dic. Keys [I] = key ){
Flag = false;
Break; // If yes, do not add
}
}
If (flag ){
Dic. Keys. push (key)
Dic. Values. push (value );
}
}
Else {
Dic. Keys. push (key)
Dic. Values. push (value );
}
Return dic;
}
/* Change key, value */
Function UpdateItem (key, value, dic ){
Var keyCount = dic. Keys. length;
If (keyCount> 0 ){
Var flag =-1;
For (var I = 0; I <keyCount; I ++ ){
If (dic. Keys [I] = key ){
Flag = I;
Break; // find the corresponding index
}
}
If (flag>-1 ){
Dic. Keys [flag] = key;
Dic. Values [flag] = value;
}
Return dic;
}
Else {
Return dic;
}
}
/* Remove key value */
Function DeleteItem (key, dic ){
Var keyCount = dic. Keys. length;
If (keyCount> 0 ){
Var flag =-1;
For (var I = 0; I <keyCount; I ++ ){
If (dic. Keys [I] = key ){
Flag = I;
Break; // find the corresponding index
}
}
If (flag>-1 ){
Dic. Keys. splice (flag, 1); // remove
Dic. Values. splice (flag, 1); // remove
}
Return dic;
}
Else {
Return dic;
}
}
/* Obtain the Key string and splice it with symbols */
Function GetKeyStr (separator, dic)
{
Var keyCount = dic. Keys. length;
If (keyCount> 0)
{
Return dic. Keys. join (separator );
}
Else
{
Return '';
}
}
/* Obtain the Value string and splice it with symbols */
Function GetValueStr (separator, dic)
{
Var keyCount = dic. Keys. length;
If (keyCount> 0)
{
Return dic. Values. join (separator );
}
Else
{
Return '';
}
}
Usage: create a global variable. You can use this global variable.
Here, I will introduce you to the discussion.
From: BirchLee's personal blog