首页 > web前端 > js教程 > 正文

创建JavaScript的哈希表Hashtable

高洛峰
发布: 2016-11-28 15:36:54
原创
1557人浏览过

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

<script type="text/javascript">
function Hashtable() {  
    this._hashValue= new Object();  
    this._iCount= 0;  
}  
 
Hashtable.prototype.add = function(strKey, value) {  
    if(typeof (strKey) == "string"){  
        this._hashValue[strKey]= typeof (value) != "undefined"? value : null;  
        this._iCount++;  
         returntrue;  
    }  
    else 
        throw"hash key not allow null!";  
}  
 
Hashtable.prototype.get = function (key) {  
    if (typeof (key)== "string" && this._hashValue[key] != typeof('undefined')) {  
        returnthis._hashValue[key];  
    }  
    if(typeof (key) == "number")  
        returnthis._getCellByIndex(key);  
    else 
        throw"hash value not allow null!";  
 
    returnnull;  
}  
 
Hashtable.prototype.contain = function(key) {  
    returnthis.get(key) != null;  
}  
 
Hashtable.prototype.findKey = function(iIndex) {  
    if(typeof (iIndex) == "number")  
        returnthis._getCellByIndex(iIndex, false);  
    else 
        throw"find key parameter must be a number!";  
}  
 
Hashtable.prototype.count = function () {  
    returnthis._iCount;  
} 
  
Hashtable.prototype._getCellByIndex = function(iIndex, bIsGetValue) {  
    vari = 0;  
    if(bIsGetValue == null) bIsGetValue = true;  
    for(var key in this._hashValue) {  
        if(i == iIndex) {  
            returnbIsGetValue ? this._hashValue[key] : key;  
        }  
        i++;  
    }  
    returnnull;  
}  
 
Hashtable.prototype.remove = function(key) {  
    for(var strKey in this._hashValue) {  
        if(key == strKey) 
        {  
            deletethis._hashValue[key];  
            this._iCount--;  
        }  
    }  
}  
 
Hashtable.prototype.clear = function () {  
    for (var key in this._hashValue) {  
        delete this._hashValue[key];  
    }  
    this._iCount = 0;  
}  
</script>
登录后复制

StringCollection/ArrayList/Stack/Queue等等都可以借鉴这个思路来对JavaScript 进行扩展。

爱图表
爱图表

AI驱动的智能化图表创作平台

爱图表 99
查看详情 爱图表
相关标签:
java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号