zoukankan      html  css  js  c++  java
  • 我知道的JavaScript数据结构之– Hashtable

     1 function Hashtable() {  
    2 this._hashValue= new Object();
    3 this._iCount= 0;
    4 }
    5 Hashtable.prototype.add = function(strKey, value) {
    6 if(typeof (strKey) == "string"){
    7 this._hashValue[strKey]= typeof (value) != "undefined"? value : null;
    8 this._iCount++;
    9 returntrue;
    10 }
    11 else
    12 throw"hash key not allow null!";
    13 }
    14 Hashtable.prototype.get = function (key) {
    15 if (typeof (key)== "string" && this._hashValue[key] != typeof('undefined')) {
    16 returnthis._hashValue[key];
    17 }
    18 if(typeof (key) == "number")
    19 returnthis._getCellByIndex(key);
    20 else
    21 throw"hash value not allow null!";
    22
    23 returnnull;
    24 }
    25 Hashtable.prototype.contain = function(key) {
    26 returnthis.get(key) != null;
    27 }
    28 Hashtable.prototype.findKey = function(iIndex) {
    29 if(typeof (iIndex) == "number")
    30 returnthis._getCellByIndex(iIndex, false);
    31 else
    32 throw"find key parameter must be a number!";
    33 }
    34 Hashtable.prototype.count = function () {
    35 returnthis._iCount;
    36 }
    37 Hashtable.prototype._getCellByIndex = function(iIndex, bIsGetValue) {
    38 vari = 0;
    39 if(bIsGetValue == null) bIsGetValue = true;
    40 for(var key in this._hashValue) {
    41 if(i == iIndex) {
    42 returnbIsGetValue ? this._hashValue[key] : key;
    43 }
    44 i++;
    45 }
    46 returnnull;
    47 }
    48 Hashtable.prototype.remove = function(key) {
    49 for(var strKey in this._hashValue) {
    50 if(key == strKey) {
    51 deletethis._hashValue[key];
    52 this._iCount--;
    53 }
    54 }
    55 }
    56 Hashtable.prototype.clear = function () {
    57 for (var key in this._hashValue) {
    58 delete this._hashValue[key];
    59 }
    60 this._iCount = 0;
    61 }

    解释:Hashtable在c#中是最常用的数据结构之一,但在JavaScript 里没有各种数据结构对象。但是我们可以利用动态语言的一些特性来实现一些常用的数据结构和操作,这样可以使一些复杂的代码逻辑更清晰,也更符合面象对象编程所提倡的封装原则。这里其实就是利用JavaScriptObject 对象可以动态添加属性的特性来实现Hashtable, 这里有需要说明的是JavaScript 可以通过for语句来遍历Object中的所有属性。但是这个方法一般情况下应当尽量避免使用,除非你真的知道你的对象中放了些什么。 

    [By the way]: StringCollection/ArrayList/Stack/Queue等等都可以借鉴这个思路来对JavaScript 进行扩展。 

     

    转载请注明出处:http://www.cnblogs.com/RobbinHan/archive/2011/12/05/2270707.html 

    本文作者: 十一月的雨 http://www.cnblogs.com/RobbinHan

  • 相关阅读:
    ENode框架Conference案例分析系列之
    ENode框架Conference案例分析系列之
    ENode框架Conference案例分析系列之
    ENode 2.6 架构与设计简介以及全新案例分享
    C#分布式消息队列 EQueue 2.0 发布啦
    EQueue 2.0 性能测试报告
    EQueue文件持久化消息关键点设计思路
    213.家庭账务管理信息系统
    212.基于DCT变换的水印算法模拟
    211.哈希表实现活期储蓄账目管理系统
  • 原文地址:https://www.cnblogs.com/RobbinHan/p/2259801.html
Copyright © 2011-2022 走看看