字典 是一种以键-值对形式存储数据的数据结构,像电话簿里面的电话和号码一样,本文字典的的基础类为Array.
字典实现:
function Dictionary() {
this.datastore = [];
this.add = add;
this.find = find;
this.remove = remove;
this.showAll = showAll;
this.count = count;
this.clear = clear;
this.kSort = kSort;
this.vSort = vSort
}
//添加
function add(key,value) {
this.datastore[key] = value;
}
//查找
function find(key) {
return this.datastore[key];
}
//删除
function remove(key) {
delete this.datastore[key];
}
//显示所有键值对
function showAll() {
for (var key in this.datastore) {
console.log(key + ':' + this.datastore[key]);
}
}
//计数
function count() {
var n = 0;
for (var key in Object.keys(this.datastore)) {
n++;
}
return n;
}
//清空字典
function clear() {
for (var key in this.datastore) {
delete this.datastore[key];
}
}
// 按键(key)排序,升序
function kSort(){
var dic = this.datastore;
var res = Object.keys(dic).sort();
for(var key in res ){
console.log(res[key] + " : " + dic[res[key]]);
}
}
// 按键(key)排序,降序
function vSort(){
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]]);
}
}
var pbook = new Dictionary();
//添加键值对
pbook.add("Mike","123");
pbook.add("David", "345");
pbook.add("Cynthia", "456");
pbook.add("Cyntddhia", "456");
//显示所有数据
pbook.showAll();
//显示数量
pbook.count();
//排序
pbook.vSort()
Map 结构的实例有以下属性和操作方法
(1)size 属性
size
属性返回 Map 结构的成员总数。
const map = new Map();
map.set('foo', true);
map.set('bar', false);
map.size // 2