首頁  >  文章  >  web前端  >  js模擬hashtable的簡單實例_javascript技巧

js模擬hashtable的簡單實例_javascript技巧

WBOY
WBOY原創
2016-05-16 16:56:461000瀏覽

複製程式碼程式碼如下:

function Hashtable()//自訂hashtable

function Hashtable()//自訂hashtable

function Hashtable()// {
    this._hash = new Object();
    this.add = function(key, value) {
      if (this. contains(key) == false) {
                this._hash[key] = typeof (value) == " 🎜>            } else {
               回復false;
            }
        } else {
        }
    這.remove = function(key) { 刪除this._hash[key]; }
this.count = function() { var i = 0; for (var k in this._hash) { i ;回我; }
    this.items = function(key) { return this._hash[key]; } }
    this.contains = function(key) { return typeof (this._hash[key]) != "undefined"; }
    this.clear = function() { for (var k in this._hash) {刪除this._hash[k]; }
}



複製程式碼複製程式碼
複製碼>

// js雜湊表
function HashTable() {

    this.ObjArr = {};

    this.Count = 0;

    //新增
    this.Add = function(key, value) {
        if (this.ObjArr.hasOwnProperty(key)) {如果已經存在,  添加
        }
        else {
           🎜>            return true;
        }
    }

    //是否包含某項
    this.Contains = function(key) {

        return this.ObjArr.hasOwnProperty(key);    //取某一項其實等價於this.ObjArr[key]
    this.GetValue = function(key) {
        if (this.Contains(key)) {
            return this. ObjArr[key];        }

        else {
                  //return;
        }
    }

    //移除
    this.Remove = function(key) {
       if (this.Contains(key)) { );            this.Count- -;
        }
    }

    //清空
    this.Clear = function() {
        this.ObjArr = {}; this.Count = 0;>
//員工
function employee(id, userName) {
    this.id = id;
    this.userName = userName;

}


function test() {

    var ht = new HashTable();
    var tmpEmployee = null;
    for (var i = 1; i  o. );
        ht.Add(i, tmpEmployee);
    }
    for (var i = 1; i         //alert(ht.ObjArr[i].userName);
    }
 >    alert(ht.Contains(1)); //false

    alert(ht.Contains(2)); //true

    //alert(ht.GetValue(1)); //異常

    //alert(ht.GetValue(1)); //異常

    //alert(ht。 >    var result = ht.GetValue(2);
    if (result != null) {
        alert("Employee Id:" result.id "fUserName:   alert("Employee Id:" result.id ";UserName:   alert("Employee Id:" result.id "; 🎜>    ht.Add(2, "這一個key已經存在!"); //Add無效
    //ht.Clear(); //清空
    alert(ht.Count);

}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn