js:数据结构笔记6--字典

Dictionary类的基础是数组不是对象;字典的主要用途是通过键取值;

基本定义:

function Dictionary() {
this.dataStore = new Array();
this.add = add;
this.find = find;
this.remove = remove;
this.showAll = showAll;
}
function add(key,value) {
this.dataStore[key] = value;
}
function find(key) {
return this.dataStore[key];
}
function remove(key) {
delete this.dataStore[key];
}
function showAll() {
var keys = Object.keys(this.dataStore),key;
for(var i = 0; i < keys.length; ++i) {
key = keys[i];
console.log(key + " -> " + this.dataStore[key]);
}
}

操作:demo

添加其他功能:

  • 统计:
    function count() {
    return Object.keys(this.dataStore).length;
    }
  • 清空:
    function clear() {
    var keys = Object.keys(this.dataStore),key;
    for(var i = 0; i < keys.length; ++i) {
    key = keys[i];
    delete this.dataStore[key];
    }
    }
  • 排序输出:对showAll进行优化
    function showSort(check,func) {
    var keys,key;
    if(check) {
    keys = Object.keys(this.dataStore).sort(func);
    } else {
    keys = Object.keys(this.dataStore);
    }
    for(var i = 0; i < keys.length; ++i) {
    key = keys[i];
    console.log(key + " -> " + this.dataStore[key]);
    }
    }  

操作:demo;

上一篇:web工程中spring+ibatis的单元测试--转载


下一篇:Windows 的命令行安装Scoop程序管理工具