Home > Article > Web Front-end > Simulate Dictionary key-value pairs in JavaScript
JavaScript often encounters some key-value pairs. In the past, it was implemented with a two-dimensional array. Today, I simply simulated the Dictionary help class.
Principle: Create an object containing two arrays, a key array and a value array, and call the JavaScript Array object method.
W3C reference address: http://www.w3school.com.cn/js/jsref_obj_array.asp
BuildDictionary() method is used to create a Dictionary object containing two arrays
AddItem method calls JavaScript’s Array object The push method is used to append key and value to the corresponding array. The
UpdateItem method is used to change the corresponding value
DeleteItem method. The Splice method of the JavaScript Array object is called to delete elements. The first parameter is the index of the element that needs to be deleted, and the first parameter represents the number of deleted elements.
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;
}
/*添加 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 (flag) {
dic.Keys.push(key)
dic.Values.push(value);
}
}
else {
dic.Keys.push(key)
dic.Values.push(value);
}
return dic;
}
/*更改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; //查找相应的index
}
}
if (flag > -1) {
dic.Keys[flag] = key;
dic.Values[flag] = value;
}
return dic;
}
else {
return dic;
}
}
/*移除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; //查找相应的index
}
}
if (flag > -1) {
dic.Keys.splice(flag,1); //移除
dic.Values.splice(flag, 1); //移除
}
return dic;
}
else {
return dic;
}
}
/*获取Key字符串,用符号拼接*/
function GetKeyStr(separator,dic)
{
var keyCount=dic.Keys.length;
if(keyCount>0)
{
return dic.Keys.join(separator);
}
else
{
return '';
}
}
/*获取Value字符串,用符号拼接*/
function GetValueStr(separator,dic)
{
var keyCount=dic.Keys.length;
if(keyCount>0)
{
return dic.Values.join(separator);
}
else
{
return '';
}
}
使用方法:创建一个全局的变量,操作这个全局变量就可以使用了。