首页 > Web开发 > 详细

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

时间:2014-10-17 15:01:34      阅读:417      评论:0      收藏:0      [点我收藏+]

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;

 

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

原文:http://www.cnblogs.com/jinkspeng/p/4030982.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!