• 我知道的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

  • 相关阅读:
    CF710F String Set Queries(AC自动机+二进制分组)
    P5231 [JSOI2012]玄武密码(AC自动机)
    AC自动机基础&应用
    [SDOI2011]计算器(快速幂,线性同余方程,BSGS)
    数论——欧拉定理和费马小定理
    AtCoder Beginner Contest 173 题解
    【CSP2019】树的重心(树的重心、倍增、换根)
    CF708C Centroids(换根dp,树的重心)
    凸包(Graham与Andrew算法求凸包)
    [USACO10MAR]Great Cow Gathering G(换根dp)
  • 原文地址:https://www.cnblogs.com/RobbinHan/p/2259801.html
Copyright © 2020-2023  润新知