>  기사  >  웹 프론트엔드  >  JavaScript 해시 테이블 만들기

JavaScript 해시 테이블 만들기

高洛峰
高洛峰원래의
2016-11-28 15:36:541169검색

해시테이블은 가장 많이 사용되는 자료구조 중 하나이지만, 자바스크립트에는 다양한 자료구조 객체가 없습니다. 그러나 동적 언어의 일부 기능을 사용하여 일반적으로 사용되는 일부 데이터 구조 및 작업을 구현할 수 있으며, 이는 일부 복잡한 코드 논리를 객체 지향 프로그래밍에서 옹호하는 캡슐화 원칙에 더 명확하고 더 부합하게 만들 수 있습니다. 이는 실제로 Hashtable을 구현하기 위해 속성을 동적으로 추가하는 JavaScriptObject 객체의 기능을 사용하는 것입니다. 여기서 설명해야 할 것은 JavaScript가 for 문을 통해 객체의 모든 속성을 탐색할 수 있다는 것입니다. 그러나 이 방법은 개체에 무엇이 들어 있는지 실제로 알지 않는 한 일반적으로 피해야 합니다.

<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(&#39;undefined&#39;)) {  
        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를 확장할 수 있습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.