const dic = {
1: "dage",
2: "erge",
3: "sange",
}
// 遍历字典
console.log("原始的字典元素: ");
for (let dicKey in dic) {
console.log(dicKey + "==" + dic[dicKey]);
}
// 添加元素
dic[4] = "sige";
// 取元素
console.log("取元素: ");
console.log(dic[4]);
const dic = [];
// 此写法与上同
// const dic = new Array();
// 添加元素
dic["name"] = "zibo";
dic["age"] = 25;
// 取元素
console.log(dic["name"]);
console.log(dic["age"]);
// 删除元素:方法一
delete dic["name"];
// 再次取元素
console.log(dic["name"]); // undefined
console.log(dic["age"]);
// 添加元素
dic["name"] = "zibo";
// 删除元素:方法二
delete dic.name;
// 再次取元素
console.log(dic["name"]); // undefined
console.log(dic["age"]);
参考文章:https://blog.csdn.net/ganyingxie123456/article/details/78163154
参考文章:https://www.cnblogs.com/xt112233/p/15126198.html
下面的操作非常有用,进行摘录!
function add(key, value){ // 添加字典的键值(key:value)
this.dataStore[key] = value;
}
function show(){ //显示字典中的键值(key:value)
for(var key in this.dataStore){
console.log(key + " : " + this.dataStore[key]);
}
}
function find(key){ // 根据键(key)查找对应的值(value),返回值value
return this.dataStore[key];
}
function remove(key){ // 根据键(key)删除对应的值(value)
delete this.dataStore[key];
}
function count(){ // 计算字典中的元素个数
var n = 0;
for(var key in Object.keys(this.dataStore)){
++n;
}
return n;
}
function kSort(){ // 字典按值(value)排序,并输出排序后的结果
var dic = this.dataStore;
var res = Object.keys(dic).sort();
for(var key in res ){
console.log(res[key] + " : " + dic[res[key]]);
}
}
function vSort(){ // 字典按值(value)排序,并输出排序后的结果
var dic = this.dataStore;
var res = Object.keys(dic).sort(function(a,b){
return dic[a]-dic[b];
});
for(var key in res ){
console.log(res[key] + " : " + dic[res[key]]);
}
}
function clear(){ // 清空字典内容
for(var key in this.dataStore){
delete this.dataStore[key];
}
}
function Dictionary(){
this.dataStore = new Array(); // 定义一个数组,保存字典元素
this.add = add; // 添加字典内容(key:value)
this.show = show; // 显示字典中的键值
this.find = find; // 根据键(key)查找并返回对应的值(value)
this.remove = remove; // 删掉相对应的键值
this.count = count; // 计算字典中的元素的个数
this.kSort = kSort; // 按键(key)排序
this.vSort = vSort; // 按值(value)排序
this.clear = clear; // 清空字典内容
}
var dic = new Dictionary(); // 构造字典类