Original article published at: http://www.birchlee.com/post/2011/10/19/27.aspx
JavaScript often encounters some key-value pairs, which were previously implemented using two-dimensional arrays. Today, we simply simulated the Dictionary help class.
Principle: Create an object containing two arrays, a key array and a value array, and call the method of the Javascript Array object.
W3C reference address: 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 JavaScript's Array object to append keys and values to the corresponding array.
UpdateItem method is used to change the corresponding value
The DeleteItem method calls the Splice method of JavaScript's Array object to delete elements. The first parameter is the index of the element to be deleted, and the first parameter represents the number to be deleted.
GetKeyStr is used to get the string after concatenating the Keys array
GetValueStr is used to get the string after concatenating the Values array.
Contains five methods in total:
/*Create 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 it exists, do not add it
}
}
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;
}
}
/*Get the Key string and concatenate it with symbols*/
function GetKeyStr(separator,dic)
{
var keyCount=dic.Keys.length;
if(keyCount>0)
{
return dic.Keys.join(separator);
}
else
{
return '';
}
}
/*Get the Value string and concatenate 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 and operate this global variable to use it.
Here's a good start