js自定义Map

原创
2014/07/07 14:35
阅读数 432

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 = function(_value) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _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;
    }
}

展开阅读全文
打赏
1
7 收藏
分享
加载中
更多评论
打赏
0 评论
7 收藏
1
分享
返回顶部
顶部