首页 > 代码库 > js自定义Map

js自定义Map

function Map() {
    this.elements = new Array();
 //得到map的大小
    this.size = function() {
        return this.elements.length;
    }
 //判断是否为空
    this.isEmpty = function() {
        return (this.elements.length < 1);
    }
    //清空
    this.clear = function() {
        this.elements = new Array();
    }
    //放进map一个对象
    this.put = function(_key, _value) {
        this.elements.push( {
            key : _key,
            value : _value
        });
    }
 //根据键去除一个对象
    this.remove = function(_key) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key && typeof this.elements[i].key == typeof _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    }
 //根据键得到一个对象
    this.get = function(_key) {
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key && typeof this.elements[i].key == typeof _key) {
                    return this.elements[i].value;
                }
            }
        } catch (e) {
            return null;
        }
    }
 //返回指定索引的一个对象
    this.element = function(_index) {
        if (_index < 0 || _index >= this.elements.length) {
            return null;
        }
        return this.elements[_index];
    }
 //是否包含键
    this.containsKey = function(_key) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key && typeof this.elements[i].key == typeof _key) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    }
 //是否包含值
    this.containsValue = http://www.mamicode.com/function(_value) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value =http://www.mamicode.com/= _value && typeof this.elements[i].value == typeof _value) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    }
 //得到所有的值
    this.values = function() {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].value);
        }
        return arr;
    }
 //得到所有的键
    this.keys = function() {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].key);
        }
        return arr;
    }
}