js 实现ActiveXObject("Scripting.Dictionary") 功能

时间:2022-05-11 14:51:45
/*
    字典
   ActiveXObject("Scripting.Dictionary")
   项目中用到的ActiveXObject("Scripting.Dictionary")
   但是要兼容谷歌 ,所以就自己写了一个字典
*/

var Dictionary = function () {
    var arr;
    var length = arr ? arr.length : 0;
};
Dictionary.prototype.add = function (Key, Item) {
    if (this.arr == null || this.arr.length == 0) {
        this.arr = new Array();
    }

    if (this.exists(Key)) {
        return; //也可以改为抛出异常
    }

    this.arr.push(new item(Key, Item));
    this.length = this.arr ? this.arr.length : 0;
}

//是否存在
Dictionary.prototype.exists = function (Key) {
    var exist = false;
    if (this.arr == null || this.arr.length == 0) {
        exist = false;
    }

    for (var i = 0; i < this.arr.length; i++) {
        if (Key == this.arr[i].Key) {
            exist = true;
            break;
        }
    }

    return exist;
}

Dictionary.prototype.remove = function (Key) {
    if (this.arr == null || this.arr.length == 0) {
        return;
    }
    var index = 0;
    for (var i = 0; i < this.arr.length; i++) {
        if (Key == this.arr[i].Key) {
            index = i;
            break;
        }
    }
    this.arr.splice(index, 1);

    this.length = this.arr ? this.arr.length : 0;
}

Dictionary.prototype.removeAll = function () {
    if (this.arr == null || this.arr.length == 0) {
        return;
    }

    this.arr.length = 0;
    this.length = this.arr.length;
}
Dictionary.prototype.set = function (Key, item) {
    if (this.arr == null || this.arr.length == 0) {
        return;
    }

    for (var i = 0; i < this.arr.length; i++) {
        if (Key == this.arr[i].Key) {
            this.arr[i].Item = item;
            break;
        }
    }
}

Dictionary.prototype.keys = function () {
    var arrKey = new Array();
    if (this.arr == null || this.arr.length == 0) {
        //return;
    }
    else {

        var arrKey = new Array();
        for (var i = 0; i < this.arr.length; i++) {
            arrKey.push(this.arr[i].Key);
        }
    }

    return arrKey;
}

function item(Key, Item) {
    this.Key = Key;
    this.Item = Item;
}